Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a module in node.js maintain state?

I have two different js files that use the same module.

file1.js:

var mod1 = require('commonmodule.js');
mod1.init('one');

file2.js:

var mod2 = require('commonmodule.js');
mod2.init('two');

(both these files file1.js, file2.js are loaded inside my server.js file, they themselves are modules)

now in commonmodule.js:

var savedName;
exports.init = function(name)
{
    savedName = name;
}
exports.getName = function()
{
    return savedName;
}

I noticed that this savedName is always overridden dependent on who set it last.So it doesn't seem to work. How would I get a module to maintain state?

Note: I also tried to set savedName as exports.savedName in the commonmodule.js but it doesn't work either

like image 889
Shai UI Avatar asked May 06 '14 18:05

Shai UI


People also ask

How do modules work in Node?

As building blocks of code structure, Node. js modules allow developers to better structure, reuse, and distribute code. A module is a self-contained file or directory of related code, which can be included in your application wherever needed. Modules and the module system are fundamental parts of how Node.

What is state in node JS?

In XState, a state node specifies a state configuration. They are defined on the machine's states property. Likewise, sub-state nodes are hierarchically defined on the states property of a state node.


2 Answers

You can just create a new instance every time the module is required:

commonmodule.js

function CommonModule() {
    var savedName;
    return {
        init: function(name) {
            savedName = name;
        },
        getName: function() {
            return savedName;
        }
    };
}

module.exports = CommonModule;

file1.js

var mod1 = new require('./commonmodule')();
mod1.init('one');
console.log(mod1.getName()); // one

file2.js

var mod2 = new require('./commonmodule')()
mod2.init('two');
console.log(mod2.getName()); // two
like image 194
Miguel Mota Avatar answered Oct 03 '22 10:10

Miguel Mota


modules in and of themselves are simple object instances. A single instance will be shared by all other modules (with the caveat that it is loaded via the same path). If you want state, use a class and export a constructor function.

example:

//Person.js
function Person(name) {
    this.name = name;
}

module.exports = Person;

To use it:

var Person = require("./Person");
var bob = new Person("Bob");
like image 38
Peter Lyons Avatar answered Oct 03 '22 09:10

Peter Lyons