在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
。
- CommonJS是同步的,但如果调用asynchronous函数会发生什么情况
- 避免重新评估和dynamic卸载用`require`调用的对象
- “错误:无法find模块”less“”Node.js模块加载偏好/订单/caching?
- 编写commonjs模块并使用require来加载它(不使用相对path)
- 如何从Node中的required()文件访问全局variables?
- 为什么在组件导出期间应用HOC而不是导入组件
- 共享节点js项目和网站项目之间的代码
- 如果我可以在node-mysql的callback中做一个“require”,那么模块函数会被添加到callback作用域还是全局作用域?
- ES6模块/节点模块重复要求还是将其作为parameter passing?