node.js - 如何覆盖 node.js 核心模块?

标签 node.js

我想使用 https://github.com/isaacs/readable-stream而不是核心 node.js stream 模块。但是我希望其他第三方模块也能使用它——是否可以在运行时覆盖核心模块?

例如我想要这样的代码:

var stream = require('stream');

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

最佳答案

您可以使用以下模块(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'));

关于node.js - 如何覆盖 node.js 核心模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926282/

相关文章:

javascript - promise 和周期

node.js - 如何在运行时更改文件夹Winston日志?

mysql - 使用 node.js/mysql connectionPool 时中止连接

javascript - Ember 查找记录并包含

JavaScript/Node.js : ES5 child class instance accessing parent class method

node.js - Stylus 和 Express - 样式表在修改时不会重新编译

node.js - 来自 Node.js 的 Amazon SNS 的 CERT_UNTRUSTED 错误响应

node.js - Node.js 在 SharePoint 上有什么用途?

javascript - Chai Framework API 不建议否定

node.js - 无法使用 bash 脚本中的 nvm