Node.js 自定义现有模块

Node.js 自定义现有模块,node.js,module,Node.js,Module,我有一个助手函数集合,我喜欢将它们与现有的实用程序模块合并在一起 不知怎的,是这样的: var customUtil = require('customUtilites'); customUtil.anotherCustomFunction = function() { ... }; exports = customUtil; 这能以某种方式实现吗?你完全可以做到 e、 g customUtilities.js: module.exports = { name: 'Custom' };

我有一个助手函数集合,我喜欢将它们与现有的实用程序模块合并在一起

不知怎的,是这样的:

var customUtil = require('customUtilites');
customUtil.anotherCustomFunction = function() { ... };

exports = customUtil;

这能以某种方式实现吗?

你完全可以做到

e、 g

customUtilities.js:

module.exports = {
  name: 'Custom'
};
module.exports = function() {
  console.log('B');
}
var customUtilities = require('./customUtilities');

customUtilities.helperA = require('./helperA');
customUtilities.helperB = require('./helperB');

module.exports = customUtilities;
var utilities = require('./bundledUtilities');
utilities.helperA();
helperA.js

module.exports = function() {
  console.log('A');
}
helperB.js:

module.exports = {
  name: 'Custom'
};
module.exports = function() {
  console.log('B');
}
var customUtilities = require('./customUtilities');

customUtilities.helperA = require('./helperA');
customUtilities.helperB = require('./helperB');

module.exports = customUtilities;
var utilities = require('./bundledUtilities');
utilities.helperA();
bundledUtilities.js:

module.exports = {
  name: 'Custom'
};
module.exports = function() {
  console.log('B');
}
var customUtilities = require('./customUtilities');

customUtilities.helperA = require('./helperA');
customUtilities.helperB = require('./helperB');

module.exports = customUtilities;
var utilities = require('./bundledUtilities');
utilities.helperA();
main.js:

module.exports = {
  name: 'Custom'
};
module.exports = function() {
  console.log('B');
}
var customUtilities = require('./customUtilities');

customUtilities.helperA = require('./helperA');
customUtilities.helperB = require('./helperB');

module.exports = customUtilities;
var utilities = require('./bundledUtilities');
utilities.helperA();

运行
node main.js
您将看到打印的
A

我建议不要修改原始模块。它可以打破依赖它的东西。相反,把它复制到一个新的对象中,然后修改它。谢谢,这就像一个符咒!我总是写不起作用的
exports={…}
module.exports={…}
正在起作用。我不知道为什么
exports={…}
返回一个空结果,而
module.exports={…}
工作正常@DeaDEnD我明白你的意思,在我的例子中,我想把这个函数添加到一个预先存在的库中:
exports.compatifileseperator=function(){return process.platform==='win32'?'\\':'/';}
因为我目前正在Win7上开发,但也希望部署在类似unix的系统上。@zaphod1984这是一个常见错误:)您可以查看
导出
模块之间的差异。导出
@谢谢您的链接。即使在官方文档中(参见圆圈示例),使用这种样式也有点误导。它可以很好地使用vor方法,但不能用于整个对象…:)无论如何,非常感谢,我想我现在很高兴。