我遇到了这个问题,可以通过Python中的导入钩子很好地解决。Node.js中是否有类似的机制,该机制允许钩子安装后拦截对require()的任何调用?
我尝试了以下操作:
originalRequire = global.require;
global.require = function(module) {
console.log('Importing ' + module + '...');
return originalRequire(module);
};
但是,这无能为力。有任何想法吗?
我已经找到了方法,只是内部有一点点。解决方案草稿:
Module = require('module');
Module.prototype.requireOrig = Module.prototype.require;
Module.prototype.require = (path) ->
console.log('Importing ' + path + '...');
return this.require(path)
这是Module
该类的源代码。
更新:这就是我的结局。它做的很简单-当需要以':/'开头的模块(例如':/ foo / bar')时,以相对于主模块的方式查找它们。
Module = require 'module'
assert = require 'assert'
do ->
origRequire = Module::require
_require = (context, path) -> origRequire.call context, path
main = require.main
Module::require = (path) ->
assert typeof path == 'string', 'path must be a string'
assert path, 'missing path'
if path[...2] == ':/'
return _require main, "./#{path[2...]}"
return _require @, path
以上代码段的等效Javascript:
var Module = require('module');
var assert = require('assert');
(function() {
var origRequire = Module.prototype.require;
var _require = function(context, path) {
return origRequire.call(context, path);
};
var main = require.main;
Module.prototype.require = function(path) {
assert(typeof path === 'string', 'path must be a string');
assert(path, 'missing path');
if (path.slice(0, 2) === ':/') {
return _require(main, "./" + path.slice(2));
}
return _require(this, path);
};
})();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句