I've came across the problem which is just fine solved by import hooks in Python. Is there similar mechanism in Node.js, that allows one to intercept any calls to require() after the hook was installed?
I've tried following:
originalRequire = global.require;
global.require = function(module) {
console.log('Importing ' + module + '...');
return originalRequire(module);
};
However this does nothing. Any ideas?
I've came across the problem which is just fine solved by import hooks in Python. Is there similar mechanism in Node.js, that allows one to intercept any calls to require() after the hook was installed?
I've tried following:
originalRequire = global.require;
global.require = function(module) {
console.log('Importing ' + module + '...');
return originalRequire(module);
};
However this does nothing. Any ideas?
Share Improve this question asked Jul 7, 2014 at 2:00 toriningentoriningen 7,5003 gold badges49 silver badges69 bronze badges 1- If anyone's wondering, this doesn't work because require is actually not a global function. It's a function that gets passed to every module. That's how relative paths are resolved. Every require function knows the path of the module it belongs to. – Fábio Santos Commented Dec 8, 2019 at 13:25
1 Answer
Reset to default 7I've found the way, it was just a bit into internals. Draft solution:
Module = require('module');
Module.prototype.requireOrig = Module.prototype.require;
Module.prototype.require = (path) ->
console.log('Importing ' + path + '...');
return this.require(path)
Here is source code for Module
class.
Update: That's what I ended with. It's doing simple thing — when requiring modules that start with ':/' (e.g. ':/foo/bar'), lookup them as they were relative to main module.
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
Equivalent Javascript for snippet above:
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);
};
})();
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745444981a4628006.html
评论列表(0条)