Sourav Chatterjee Sourav Chatterjee - 2 months ago 15
Node.js Question

ES6 Class and module.exports

I am seeing this pattern these days for nodeJS implementation, where in we have the following code for my Module:

class Foo {
bar() {
console.log('bar');
}
}
module.exports = Foo;


Then when I do a require and finally say new to create an instance of the class.

var Foo = require(./foo);
var myFoo = new Foo();
myFoo.bar();


This pattern according to me will keep creating multiple instances of class Foo, everytime it is called.

The other pattern could have been what i am used to where in my foo.js would be.

module.exports = {
bar: function() {
console.log('bar');
}
};


And then i just require and call bar.

var foo = require(./foo);
foo.bar();


Question would these two behave the same? Will the second pattern keep creating objects everytime I require and call bar on the object?

Isn't creating singleton pattern a good idea in case 1 as we are used to in other languages, wherein we keep serving the same instance if it has already been created once?

Answer

This pattern according to me will keep creating multiple instances of class Foo, everytime it is called.

Yes, that's the purpose. Though new Foo(); is only executed once in your example as well.

would these two behave the same?

No.

Will the second pattern keep creating objects everytime I require and call bar on the object?

No. require() calls are cached, they return the same module every time.

Isn't creating singleton pattern a good idea?

No, a singleton is rarely a good idea if it contains any state. Your example does not, but where classes are used in Node.js they usually do.

Comments