【问题标题】:Import hooks in Node.js在 Node.js 中导入钩子
【发布时间】:2014-07-07 02:00:45
【问题描述】:

我遇到了一个问题,这可以通过 Python 中的导入钩子很好地解决。 Node.js 中是否有类似的机制,允许在安装钩子后拦截对 require() 的任何调用?

我尝试了以下方法:

originalRequire = global.require;

global.require = function(module) {
    console.log('Importing ' + module + '...');

    return originalRequire(module);
};

但是,这什么也没做。有什么想法吗?

【问题讨论】:

  • 如果有人想知道,这是行不通的,因为 require 实际上不是全局函数。这是一个传递给每个模块的函数。这就是解决相对路径的方式。每个 require 函数都知道它所属模块的路径。

标签: javascript node.js hook require


【解决方案1】:

我找到了方法,只是有点内部结构。解决方案草案:

Module = require('module');
Module.prototype.requireOrig = Module.prototype.require;
Module.prototype.require = (path) ->
    console.log('Importing ' + path + '...');

    return this.require(path)

HereModule 类的源代码。

更新:这就是我的结束。它做的很简单——当需要以 ':/' 开头的模块时(例如 ':/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

上面sn-p的等效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);
    };
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2019-11-07
    相关资源
    最近更新 更多