I am trying to organize a Node.js application developed with Express 4 and am confused about the scope of modules which are imported with require().
Imagine that I use require('./services/user')
to import a service in a module such as routes/user.js:
var userService = require('./services/user');
Then I do the same require('./services/user')
in another module routes/department.js.
My question is: is userService the same instance in user.js and department.js or each of them has it's own userService object? That is to say, once you've exported some element through module.exports = XXX if you require the same file, will you get always the same instance? Could you show me where in the Node.js docs that's specified?
In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
The require function will look for files in the following order. NPM Modules. It will look in the node_modules folder. Local Modules.
A module in RequireJS is a scoped object and is not available in the global namespace. Hence, global namespace will not be polluted. RequireJS syntax allows to load modules faster without worrying about keeping track of the order of dependencies. You can load multiple versions of the same module in the same page.
You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).
If I understand your question correctly, you have theses files:
.
|_. app.js
|_. routes/
|_. user.js
|_. department.js
|_. services/
|_. user
And your code do this:
app.js call user.js
user.js call user
app.js call department.js
department.js
In that case, at the first time user is required, it is put on cache in require.cache
.
Then the second time it is called, the caller get require.cache['./service/user']
, where is stored your object.
As such, you do have the same object in both department.js and user.js.
Source:
EDIT:
Other helpful links:
node.js require() cache - possible to invalidate?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With