0

カスタム モジュールがあり、 first で初期化するメソッドを提供したいのですがrequire、後続の require でオブジェクトを直接返します。

ただし、モジュールは最初に要求されたときにキャッシュされるため、後続の要求は直接返すのではinitなく、関数を返す必要がありobjます。

サーバー.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.

モジュール.js:

var obj = null;

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

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

どうすればその問題を回避できますか? それとも、それを達成するための確立されたパターンはありますか?

しかし、私はobjキャッシュを保持initしたいと考えていますrequire

4

1 に答える 1

2

必要なキャッシュをクリアするには、いくつかの方法があります。ここで確認できますnode.js require() キャッシュ - 無効にできますか? しかし、これは良い考えではないと思います。必要なモジュールを渡すことをお勧めします。つまり、一度だけ初期化し、他のモジュールに配布します。

サーバー.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
}

モジュール.js:

var obj = null;

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

module.exports = { init: init };
于 2013-08-28T12:59:27.577 に答える