简体   繁体   中英

global variables in modules using node / express.js

I am trying to avoid using global variables in my server.js file but need variables accessible and writable by various functions. However, I am unsure if scope works the same way as on the client side (since it seems more 'hidden'). I read somewhere that modules have their own scope but if I place variables there and they are accessible in server.js isn't that the same thing as a global scope? For example:

//module.js

var config = [
  {var1: 1},
  {var2: 2},
  {var3: 3}
]

module.exports = {
  config
};

//server.js
const { config } = require("./config.js")

function function1() {
  var a = config[0].var1
  bar b = config[0].var2

  config[0].var3 = a+b // changing var3 value in module

}

Is using modules this way acceptable? If not what would be considered a better practice here?

Thanks

each module has own scope but you can import or export any of variables , functions and etc to other modules and use them in there, like change value of variables but the value will change in module that you imported , not in main

run code below and I think it works as you want it to.

//module.js
var config = [
  {var1: 1},
  {var2: 2},
  {var3: 5} 
]

console.log(config[2].var3) //5

module.exports = config

//server.js
const  config  = require("./app.js")

function function1() {
  var a = config[0].var1
  var b = config[1].var2

  config[2].var3 = a+b // changing var3 value in module
  console.log(config[2].var3) 
}
function1() //3
console.log(config[2].var3)//3


//client.js
const  config  = require("./app.js")
console.log(config[2].var3) //5

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