Node.js: Declare Node_modules Globally, Or Locally On A As-needed Basis?
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)?
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.
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error