如何覆盖Node.js核心模块?

4
我想使用https://github.com/isaacs/readable-stream代替核心的node.js stream模块。但我也希望其他第三方模块也能使用它-在运行时覆盖核心模块是否可行?
例如,我希望这段代码:
var stream = require('stream');

返回readable-stream库而不是核心stream模块。

1个回答

3
您可以使用以下模块(mock-require.js):
'use strict';

var Module = require('module');
var assert = require('assert');

var require = function require(path) {
    assert(typeof(path) == 'string', 'path must be a string');
    assert(path, 'missing path');

    var _this = this;
    var next = function() { return Module.prototype.require.next.apply(_this, arguments); };

    console.log('mock-require: requiring <' + path + '> from <' + this.id + '>');

    switch (path) {
        case 'stream':
            // replace module with other
            if (/\/readable-stream\//.exec(this.filename)) {
                // imports from within readable-stream resolve into original module
                return next('stream');
            } else {
                return next('readable-stream');
            }

        case 'events':
            // mock module completely
            return {
                EventEmitter: next('eventemitter2').EventEmitter2,
                usingDomains: false
            }

        case 'hello/world :)':
            // name can be anything as well
            return { hello: 'world!' };

        default:
            // forward unrecognized modules to previous handler
            console.log(path);
            return next(path);
    }
};

require.next = Module.prototype.require;

Module.prototype.require = require;

module.exports = {};

您需要在项目中的某个地方引用它一次,以确保 require() 被正确拦截。您也可以自由地提供一些灵活的API来注册/注销模拟模块(类似于 require.filter(/^foo\/\d+/, function(path) { return { boo: 'hoo' }; }); — 我还没有去烦恼它。

然后使用示例如下:

'use strict';

require('./mock-require');

require('util');

console.log(require('hello/world :)'));
console.log(require('events'));
console.log(require('stream'));

1
我已经修复了stream的导入错误,这是由于循环依赖引起的,因为readable-stream依赖于stream,而stream本身在readable-stream内部解析为readable-stream。我已经将其修复为根据调用位置解析为不同的模块。 - toriningen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接