node.js - 需要 Node 模块的新实例

标签 node.js node-modules

其中一个模块中应该需要第三方模块的新实例。

// 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/

相关文章:

javascript - Mongoose getter正在获取未定义的参数

node.js - 这个 sequelize 查询有什么问题

javascript - 如何通过调用 ajax 将 html 表单数据发送到 node.js 服务器?

node.js - 如何修复 'fs: re-evaluating native module sources is not supported' - 优雅的 fs

javascript - Nodejs运行js文件的流程

node.js - NodeJS - 在 Linux 中找不到自定义模块。在 Windows 中工作正常

javascript - 在 node-cron 中获取下一个 cron 作业时间

node.js - 如何自动更新所有 Node.js 模块?

javascript - MongoDB Mongoose 聚合/数学运算

ruby - Nginx与后端服务器之间的IPC机制是怎样的?