简体   繁体   中英

Import hooks in Node.js

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 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 ':/' (eg ':/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);
    };
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM