require()
ing all of our code in a Node.js script is taking a while. How can I instrument require()
to see what's being loaded?
require()我们在Node.js脚本中的所有代码需要一段时间。如何检测require()以查看正在加载的内容?
This is difficult because, according to the docs,
这很难,因为根据文档,
require
isn't actually a global but rather local to each module.require实际上并不是全局的,而是每个模块的本地。
So this doesn't work:
所以这不起作用:
(function() {
var slice = [].slice;
var old = global.require;
global.require = function() {
var args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
console.log("REQUIRE", args); // Log it!
return old.apply(null, args);
};
})();
Any ideas?
有任何想法吗?
1 个解决方案
#1
3
You can override require, it's defined in node/lib/module.js. Same module
is passed to all files being required. If you change reference in the first file, it'll be reused later.
您可以覆盖require,它在node / lib / module.js中定义。将相同的模块传递给所需的所有文件。如果您在第一个文件中更改引用,它将在以后重用。
_oldRequire = module.require;
module.require = function(id) {
var ts = process.hrtime();
var res = _oldRequire.call(module, id);
var t = process.hrtime(ts);
console.log('require(\'%s\') took %s ms', id, t[0]*1000 + t[1]/1e6);
return res;
};
require('./test123.js');
Update - version which propagates properly to nested require:
更新 - 正确传播到嵌套的版本需要:
var Module = require('module');
_oldRequire = Module.prototype.require
Module.prototype.require = function(id) {
var ts = process.hrtime()
var res = _oldRequire.call(this, id);
var t = process.hrtime(ts)
console.log('require(\'%s\') took %s ms', id, t[0]*1000 + t[1]/1e6)
return res;
}
#1
3
You can override require, it's defined in node/lib/module.js. Same module
is passed to all files being required. If you change reference in the first file, it'll be reused later.
您可以覆盖require,它在node / lib / module.js中定义。将相同的模块传递给所需的所有文件。如果您在第一个文件中更改引用,它将在以后重用。
_oldRequire = module.require;
module.require = function(id) {
var ts = process.hrtime();
var res = _oldRequire.call(module, id);
var t = process.hrtime(ts);
console.log('require(\'%s\') took %s ms', id, t[0]*1000 + t[1]/1e6);
return res;
};
require('./test123.js');
Update - version which propagates properly to nested require:
更新 - 正确传播到嵌套的版本需要:
var Module = require('module');
_oldRequire = Module.prototype.require
Module.prototype.require = function(id) {
var ts = process.hrtime()
var res = _oldRequire.call(this, id);
var t = process.hrtime(ts)
console.log('require(\'%s\') took %s ms', id, t[0]*1000 + t[1]/1e6)
return res;
}