其中一个模块中应该需要第三方模块的新实例。
// a
...
exports.thirdParty = require('third-party');
<小时/>
// b
...
exports.thirdParty = require('third-party');
<小时/>
// first-party
...
exports.thirdParty = requireFreshInstance('third-party');
<小时/>
// app.js
var assert = require('assert');
var a = require('a');
var firstParty = require('first-party');
var b = require('b');
assert(a.thirdParty === b.thirdParty);
assert(firstParty.thirdParty !== a.thirdParty);
assert(firstParty.thirdParty !== b.thirdParty);
所有列出的模块都有类似的软件包要求,
dependencies: {
"third-party": "^1"
}
并且要求它应该保持完整,不允许使用像 "thirdparty": "git://..."
这样的技巧。
假设用户仅控制first-party
模块,并且无法修改third-party
模块以拥有新的factory
方法将返回一个新实例。
我知道,如果所有情况下版本都相同,third-party
就会被缓存一次(从技术上讲,它是 third-party
的完整路径)这很重要),很可能所有对象中的 .thirdParty
属性都是相等的。
如何在 Node.js 中以编程方式(而不是使用 package.json)解决这个问题?
最佳答案
这是一个模块 require-new
可以满足您的要求。
require-new
需要一个新的模块对象。require-new
不影响 require 的状态或行为 方法。require-new
被设计用于模块测试。
以下是该模块的示例。
require('./rand.js'); // 0.697190385311842
require('./rand.js'); // 0.697190385311842
模块在需要时会缓存在 require.cache
对象中。
require-new
从与您请求的模块关联的 require.cache
对象中删除键值,从而使模块重新加载:
requireNew('./rand.js'); // 0.2123227424453944
requireNew('./rand.js'); // 0.5403654584661126
关于node.js - 需要 Node 模块的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35616339/