Node.js监听模块加载
通过前端的RequireJS,我们可以监听模块何时被加载到运行时模块caching中,使用:
requirejs.onResourceLoad = function (context, map, depArray) { console.log('onResourceLoad>>>', 'map.id:', map.id, 'context:', context); };
我们可以用Node.js做些什么吗? 将对debugging有用。 特别是当服务器根据configuration加载不同的文件(或以不同的顺序)时。
我认为这可能logging在
https://nodejs.org/api/modules.html
但我什么也没有看到
如果你看看require()
的源代码 ,你会发现:
Module._load = function(request, parent, isMain) { if (parent) { debug('Module._load REQUEST %s parent: %s', request, parent.id); }
这表明您可以利用debug()
调用来获取所需的信息。 为了做到这一点,你会注意到这个模块是使用util.debuglog('module')
。 这意味着你需要用设置为module
的NODE_DEBUG
variables来运行你的应用程序。 您可以通过以下方式从控制台执行此操作:
NODE_DEBUG=module node main.js
这将logging你在找什么。
因为node.js模块是同步导入(必需)的,所以简单地使用require语句意味着模块被导入。
虽然RequireJS可以asynchronous地导入模块,但是Even Listening却是一个重要的特性,但是Node.js中的本地需求却不需要。 这样,你可能知道:
const module = require('module') // You can use the module here, async or sync.
为了补充说明,不仅需要同步,而且为了使用模块,它必须在使用它的相同文件中明确要求。 这可以通过几种方式绕过,但最好的做法是要求每个模块使用一个模块。
对于需要asynchronous初始化的特定模块,模块应该提供一个事件,也可以使用承诺或callback来包装init函数。 例如,使用承诺:
const module = require('module') // Create a promise to initialize the module inside it: const initialized = new Promise((resolve, reject) => { // Init module inside the promise: module.init((error) => { if(error){ return reject(error) } // Resolve will indicate successful init: resolve() }) }) // Now with wrapped init, proceed when done: initialized .then(() => { // Module is initialized, do what you need. }) .catch(error => { // Handle init error. })
我没有意识到为模块加载callback( 尽pipe模块加载的日志logging机制似乎存在 )的文档callbackAPI。
下面是一个快速的解决方法,通过monkeypatching Module._load
明显缺乏这种callback:
const Module = require('module'); const originalModuleLoad = Module._load; Module._load = function() { originalModuleLoad.apply(this, arguments); console.log("Loaded with arguments " + JSON.stringify(arguments)); }
我在REPL中执行了上面的代码,然后确实require('assert')
。 你瞧,
> require('assert') Loading with arguments {"0":"assert","1":{"id":"<repl>","exports":{},"filename":null,"loaded":false,"children":[],"paths":["/Users/mz2/Projects/manuscripts-endnote-promo/repl/node_modules","/Users/mz2/Projects/manuscripts-endnote-promo/node_modules","/Users/mz2/Projects/node_modules","/Users/mz2/node_modules","/Users/node_modules","/Users/mz2/.nvm-fish/v6.1.0/lib/node_modules","/Users/mz2/.node_modules","/Users/mz2/.node_libraries","/Users/mz2/.nvm-fish/v6.1.0/lib/node"]},"2":false}
请不要考虑使用类似上面的代码,除了debugging目的。