How can I override the main node.js module?

I would like to use https://github.com/isaacs/readable-stream instead of the main node.js module stream

. However, I would like other third party modules to use it as well - is it possible to override the main module at runtime?

For example, I would like to receive this code:

var stream = require('stream');

      

to return the library readable-stream

instead of the main module stream

.

+3


source to share


1 answer


You can use the following module ( 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 = {};

      

You need to require it somewhere in your project, so it require()

will be intercepted correctly. You can also provide some flexible API to register / register registration modules (something like require.filter(/^foo\/\d+/, function(path) { return { boo: 'hoo' }; });

- I haven't bothered yet).



Usage example:

'use strict';

require('./mock-require');

require('util');

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

      

+2


source







All Articles