在Node.js中安全且正确地monkeypatching require函数

monkeypatching node.js中的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); }; 

然而,这不是很有效,我不知道为什么。 我从debugging模块得到这个错误:

 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) 

如果我的代码是好的,那么也许我应该仔细看看debugging模块在做什么?

你没有返回结果:

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

没有那个return你的包装总是返回undefined