Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a node.js module instance created for each require?

I am trying to solve a bug in a node.js application.

In a module called mmm, I have a local variable (not exported) called xxx which is set to false. There is an exported function called enableXXX() which sets the variable to true. Another module nnn requires mmm and calls enableXXX().

Other modules require mmm, but it seems that the call to enableXXX() has not been performed. It behaves as if xxx is still false.

Do it mean each require create a separate instance of the module?

Update

I turns out it was a wrong upcase letter in a require:

// Module A
var XXX = require("./myDir/xxx.js");
...

// Module B
var XXX = require("./mydir/xxx.js");
...
like image 809
Jérôme Verstrynge Avatar asked Dec 20 '22 14:12

Jérôme Verstrynge


2 Answers

No, it doesn't. Let's make an experiment:

mmm.js:

var xxx = false;

exports.enableXXX = function() {
    xxx = true;
}

exports.isEnabled = function() {
    return xxx;
}

nnn.js:

require('./mmm').enableXXX();

main.js:

require('./nnn');

console.log('The result is: ' + require('./mmm').isEnabled());

Now let's run main.js:

$ node main.js
The result is: true

And here is an explanation from the official docs:

  • Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
like image 196
Oleg Avatar answered Dec 22 '22 02:12

Oleg


Here is a link to the node documentation. You should read the section about caching AND the caveat section: http://nodejs.org/api/modules.html#modules_caching

like image 21
Ray Stantz Avatar answered Dec 22 '22 02:12

Ray Stantz