简体   繁体   中英

node.js global variables use?

global.test = "test";
console.log(global.test); //test 

but I want to do this

console.log(test); //test

not use

var test = global.test;

How can I do it? I want any module in my project not need to assign all global scope variable in ecah scope to use these global node.js global variables.

Properties you add to the global object become global variables, so:

global.test = "foo";
console.log(test); // "foo"

But using global variables is almost always a bad idea. Instead, put the thing you want to share in a module, and load that module into other modules that need to use it:

test.js :

exports.test = "foo";

Anything that needs to use it:

var test = require("./test.js").test;
console.log(test);

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