2017-03-19 30 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

就是这样,谢谢! –

相关问题