Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 964
toriningen Avatar asked Sep 02 '25 03:09

toriningen


1 Answers

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 ':/' (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);
    };
})();
like image 164
toriningen Avatar answered Sep 04 '25 17:09

toriningen