我想使用 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/