Domanda

I have a custom module and would like to provide a method to initialize it on first require, but directly return an object on subsequent requires.

But the module gets cached when first required and therefore subsequent requires still return the init function instead of returning obj directly.

server.js:

var module = require('./module.js');
var obj = module.init();
console.log('--DEBUG: server.js:', obj); // <-- Works: returns `obj`.

require('./other.js');

other.js:

var obj = require('./module.js');
console.log('--DEBUG: other.js:', obj); // <-- Problem: still returns `init` function.

module.js:

var obj = null;

var init = function() {
    obj = { 'foo': 'bar' };
    return obj;
};

module.exports = (obj) ? obj : { init: init };

How can I work around that problem? Or is there an established pattern for achieving such?

But I would like to keep obj cached, because my real init does some work I would rather not do on every require.

È stato utile?

Soluzione

There are some ways to clear the require cache. You may check here node.js require() cache - possible to invalidate? However, I think that this is not a good idea. I'll suggest to pass the module which you need. I.e. initialize it only once and distribute it to the other modules.

server.js:

var module = require('./module.js');
var obj = module.init();

require('./other.js')(obj);

other.js:

module.exports = function(obj) {
    console.log('--DEBUG: other.js:', obj); // <-- The same obj
}

module.js:

var obj = null;

var init = function() {
    obj = { 'foo': 'bar' };
    return obj;
};

module.exports = { init: init };
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top