Rockstar5645
Rockstar5645

Reputation: 4518

module.exports and local variables

I'm trying to create a small web app and I have a question about module.exports

supppose I have a file counter.js

var counter = 0;

module.exports = {
    add: function() {
        counter++;
    }, 
    get: function() {
        return counter;
    }
}

and I try to reference this file in several files suppose app.js and count.js all located in the same directory

// from app.js

var a = require('./counter.js');

a.add(); 
console.log(a.get()); // the value is 1


// from count.js

var b = require('./counter.js');

b.add(); 
console.log(b.get()); // the value is 2?

will the value be 1 or 2?

Upvotes: 0

Views: 2372

Answers (2)

Trott
Trott

Reputation: 70075

If you mean that (for example) app.js will include count.js via require() or that both app.js and count.js will be included by a third file via require(), then they all share an instance and the answer is 2.

If you mean what happens if you run node app.js and then run node count.js, then in that case, every file gets its own instance of the required module, so it will be 1.

Upvotes: 1

Borja Tur
Borja Tur

Reputation: 817

The result will be 2

From nodejs.org doc

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.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

Upvotes: 1

Related Questions