Ad

Node.js: Declare Node_modules Globally, Or Locally On A As-needed Basis?

- 1 answer

Should node_modules dependencies be declared globally at the start of the application code, or declared locally at the point they're required? I'm wondering if there's a best practice.

For example, I bootstrap my application using an index.js and require scripts when they're needed. My security.js module might, for example, need use of node_hash. Now, should I require that in security.js as

var node_hash = require('node_hash')

or globally require it in index.js so it's available to security.js (but also everything else)?

Ad

Answer

In Node, there's not really a concept of "require globally." When you require a module into another module, the required module is only available in the module you required it into. If you want to use that required module elsewhere, you will need to require it again (or somehow pass the returned object into your other modules).

Thus, the correct (only, really) answer is to require them where needed. Note that Node uses a require cache, so the required module is only really evaluated once, and the same object is returned for multiple requires of the same file.

[Edit] Assigning to a variable declared without var assigns it to the global scope (e.g. it can be accessed via global in Node). Very rarely do you want to do this; not only does it make it difficult to determine where a variable was declared, but it can also cause namespacing issues.

Ad
source: stackoverflow.com
Ad