1
我有一個幫助函數集合,我喜歡將它們與現有的實用程序模塊合併在一起。定製現有模塊
不知怎的,像這樣:
var customUtil = require('customUtilites');
customUtil.anotherCustomFunction = function() { ... };
exports = customUtil;
這能以某種方式實現?
我有一個幫助函數集合,我喜歡將它們與現有的實用程序模塊合併在一起。定製現有模塊
不知怎的,像這樣:
var customUtil = require('customUtilites');
customUtil.anotherCustomFunction = function() { ... };
exports = customUtil;
這能以某種方式實現?
你完全可以這樣做。
例如
customUtilities.js:
module.exports = {
name: 'Custom'
};
helperA.js
module.exports = function() {
console.log('A');
}
helperB.js:
module.exports = function() {
console.log('B');
}
個bundledUtilities.js:
var customUtilities = require('./customUtilities');
customUtilities.helperA = require('./helperA');
customUtilities.helperB = require('./helperB');
module.exports = customUtilities;
main.js:
var utilities = require('./bundledUtilities');
utilities.helperA();
運行node main.js
你會看到A
打印。
我建議不要修改原始模塊。它可以打破依賴它的東西。相反,將它複製到一個新的對象並修改它。 – fent 2012-01-16 19:27:11
謝謝,像魅力一樣工作!我總是寫'exports = {...}'不起作用,'module.exports = {...}'正在工作。我不知道爲什麼'exports = {...}'返回一個空的結果,而'module.exports = {...}'工作正常。 @deaDEnD我明白了你的觀點,在我的情況下,我想將此函數添加到預先存在的庫中:'exports.compatFileSeperator = function(){return process.platform ==='win32'? '\\':'/'; };'因爲我目前正在Win7上開發,但也想在像unix這樣的系統上部署。 – zaphod1984 2012-01-16 20:06:39
@ zaphod1984這是一個常見的錯誤:)你可以檢查出http://stackoverflow.com/questions/6116960/what-do-module-exports-and-exports-methods-mean-in-nodejs之間的差異'出口'和'module.exports'。 – qiao 2012-01-17 04:59:28