简体   繁体   中英

How bad it is to use global variables in nodejs?

I need libraries (mongo, async ...) and some core function in almost every files of my code. As far has i understand, loading a module is an expensive process. Plus, writing x more line of code in every file is a pain.

So wouldn't it be smarter to require it once, when the application start ?

I know that global variables are bad in general, but how bad it is in this context ?

It is always a BAD (intentionally uppercase) idea to use global variables, so you should watch out for another solution.

Since modules get cached when they are loaded, they are not too expensive. It does not matter whether you do it once or multiple times.

So the easiest way is to require a module everywhere you need it.

Now, sometimes a module needs some configuration. Then you need to make sure that this is done when the module is loaded for the first time. For this, create a wrapper module like this:

var foo = require('foo');

foo.configure(options);
// Or do whatever you need to do here to configure foo.

module.exports = foo;

Now you can use it like this:

var configuredFoo = require('./configuredFoo');

This should do the trick.

Loading a module for the first time is somewhat expensive (though it only occurs at server startup and it's usually loading from a local hard drive, not over the network). But, after it's been loaded once, it is cached by node.js and subsquent require() calls for the same module simply return the exact same module very quickly without doing any additional loading.

So, having multiple modules share the same sub-modules via require() is an efficient and intended way to design your node.js code without using a single global variable.

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