简体   繁体   中英

Node.js: How can I export value to another route?

How can I export a specific variable from one route to another route? The aim here is to export a variable and access the value in a different router file.

So far I have tried, but it's not working:

module.exports = {
  router: router,
  myVariabel: myVariabel
}

//Swediek

You have to export and import the variable. Let's say exporting a function add from this file.

function add(x, y) {
   return x + y;
}

function subtract(x, y) {
   return x - y;
}

// Adding the code below to allow importing
// the functions in other files
module.exports = { add }

Now need to import it from another file where want to use this function.

// Importing the func.js module

// The ./ says that the func module
// is in the same directory as
// the main.js file
const f = require('./func');

// Require returns an object with add()
// and stores it in the f variable
// which is used to invoke the required

const result = f.add(10, 5);

console.log('The result is:', result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM