Override the require function

Is it possible to override the global require function, affecting it at process level?

From what I know, the require function is provided as argument in the function that wraps the NodeJS scripts:

(function (..., require, __dirname) { // something like this
   // The wrapped code

Is there any way to modify the require function?

(function () {
    var _require = require;
    require = function () {
        _require.apply(this, arguments);

This will probably affect only the script where it's located.

How can we modify it at the process level?


var Module = require('module');
var originalRequire = Module.prototype.require;

Module.prototype.require = function(){
  //do your thing here
  return originalRequire.apply(this, arguments);

mock-require does this by overriding Module._load (which is what the real require actually calls).

Here is a much safer native ES6 answer based on @orourkedd which acts like an event listener on all require calls, It might look like its replacing require but if you look closer its actually saying: require = require and trap calls to it but return original behaviour. This is just one of the millions of uses of Proxy() which has been really handy for me, for example in Typescript for mapping tsconfig "paths" with the real module node will resolve.

I would go as far as to say that this is not "Monkey patching" as its on a lower level of the language.

var Module = require('module');
Module.prototype.require = new Proxy(Module.prototype.require,{
    apply(target, thisArg, argumentsList){

        let name = argumentsList[0];

        /*do stuff to ANY module here*/

            /*do stuff to MY module*/
            name = "resolveAnotherName"

        return Reflect.apply(target, thisArg, argumentsList)

This is the workaround I found. If there is any better solution, I'm open to see it.

I created a script named req-modifier.js:

module.exports = function (_args) {

    var _require = _args[1];
    function newRequire () {
        console.log("Require is called");
        return _require.apply(this, arguments);
    newRequire.__proto__ = _require;

    _args[1] = newRequire;

Then from the files I want to modify the require function, I do:


var foo = require("./foo");

The limitation is that I have to call every time the req-modifier function.

Need Your Help

Is passing pointer argument, pass by value in C++?

c++ function pointers pass-by-value

Is passing pointer argument, pass by value in C++? Since i see that any change to the pointer as such is not reflected outside the method. The changes i do by dereferencing the pointer is reflected


php url-parsing

I recently was seeking a way to properly determine protocol, under which url request was supplied to the server.