如何在 Node.js 中记录所有 require() ?

a p*_*erd 1 node.js

require()在 Node.js 脚本中处理所有代码需要一段时间。我如何通过仪器require()来查看正在加载的内容?

这很困难,因为根据文档,

require实际上不是全局的,而是每个模块的本地的。

所以这不起作用:

(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);
  };
})();
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

And*_*rov 5

您可以覆盖 require,它在 node/lib/module.js 中定义。相同的内容module会传递给所有需要的文件。如果您更改第一个文件中的引用,稍后将重复使用它。

_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');
Run Code Online (Sandbox Code Playgroud)

更新- 正确传播到嵌套需求的版本:

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;
}
Run Code Online (Sandbox Code Playgroud)