2017-03-19 55 views
1

在node.js中修改require函數可能證明是有用的,特別是對於某些庫。我試圖找出我怎麼能這樣做的權利,安全等在Node.js中安全並正確地monkeypatching require函數

以下是我有:

const Mod = require('module'); 

const req = Mod.prototype.require; 

Mod.prototype.require = function() { 
    // do some side-effect of your own 
    req.apply(this, arguments); 
}; 

然而,這是不是很的工作,我不知道爲什麼。我得到這個錯誤從調試模塊:

TypeError: Cannot set property 'init' of undefined 
    at Object.<anonymous> (/Users/alexamil/WebstormProjects/oresoftware/sumanjs/suman/node_modules/debug/src/node.js:15:14) 
    at Module._compile (module.js:571:32) 
    at Object.Module._extensions..js (module.js:580:10) 
    at Module.load (module.js:488:32) 
    at tryModuleLoad (module.js:447:12) 
    at Function.Module._load (module.js:439:3) 
    at Module.require (module.js:498:17) 
    at Module.Mod.require (/Users/alexamil/WebstormProjects/oresoftware/sumanjs/suman/lib/index.js:11:9) 
    at require (internal/module.js:20:19) 
    at Object.<anonymous> (/Users/alexamil/WebstormProjects/oresoftware/sumanjs/suman/node_modules/debug/src/index.js:9:20) 

如果我的代碼是OK,那麼也許我應該採取什麼調試模塊是做仔細看看?

回答

2

你沒有返回結果:

Mod.prototype.require = function() { 
    // do some side-effect of your own 
    return req.apply(this, arguments); 
}; 

沒有這種return您的包裝總是返回undefined

+0

就是這樣,謝謝! –

相關問題