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);
};
但是这不是很有效,我不确定为什么。我从调试模块中得到这个错误:
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)
如果我的代码没问题,那么也许我应该仔细看看调试模块在做什么?
最佳答案
你没有返回结果:
Mod.prototype.require = function () {
// do some side-effect of your own
return req.apply(this, arguments);
};
如果没有 return
,您的包装器将始终返回 undefined
。
关于javascript - 在 Node.js 中安全且正确地猴子修补 require 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883486/