How can a module be supported in node.js?

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 of 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 saved name is always overridden depending on who installed it last. Therefore, it does not work. How do I get a module to maintain state?

Note. I also tried setting savedName as export.savedName in commonmodule.js, but it does not work either

+4
source share
4 answers

. ( , ). , .

:

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

module.exports = Person;

:

var Person = require("./Person");
var bob = new Person("Bob");
+2

, :

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
+2

/; mod1 mod2 - . , - - ,

var mod = require('commonmodule.js');
var state = new mod.init('one');

init . , new (, var state = require('commonmodule.js').init('one');)

(, , , , .)

0
source

Perhaps you can remove your module from the cache. For instance:

file1.js:

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

file2.js:

delete require.cache[require.resolve(modulename)];

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

But I do not think it is very convenient and clean.

But you can also clone it or make a small proxy.

You can also create classes:

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

Then:

var mod2 = new (require('commonmodule.js'))();
mod2.init('two');
-1
source

Source: https://habr.com/ru/post/1539478/


All Articles