覆盖require函数 [英] Override the require function
本文介绍了覆盖require函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以覆盖全局 require
函数,在进程中影响它
等级?
Is it possible to override the global require
function, affecting it at process
level?
据我所知, require
函数在包装NodeJS脚本的函数中作为参数提供:
From what I know, the require
function is provided as argument in the function that wraps the NodeJS scripts:
(function (..., require, __dirname) { // something like this
// The wrapped code
})(...);
有没有办法修改 require
函数?
(function () {
var _require = require;
require = function () {
console.log("...");
_require.apply(this, arguments);
};
})();
这可能只影响它所在的脚本。
This will probably affect only the script where it's located.
我们如何在流程级别修改它?
How can we modify it at the process level?
推荐答案
var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function(){
//do your thing here
return originalRequire.apply(this, arguments);
};
这篇关于覆盖require函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文