Override function of a Node.js module

Override function of a Node.js module – There could be scenarios where you would like to improve the functionalities of existing modules by overriding them.

In this tutorial, we shall learn to override a function of a Node.js module.

Steps to Override Function of a Module in Node.js

To override an existing function of a Node.js module, following is a step by step guide.

Step 1: Include the module.

The first step to override a function in a module is to include the module itself using require function.

var newMod = require('<module_name>');

We have retrieved the module to a variable.

Step 2: Delete function from the module variable.

Using variable to the module,newMod , delete the function from it using following syntax.

delete newMod['<function_name>'];

Please remember that the changes would be only to the module variable, newMod, but not to the original module itself.

Step 3: Add function, with same name, to the module variable.

Using variable to the module,newMod , add the function with the same name, that we deleted in the previous step, using following syntax.

newMod.<function_name> = function(function_parameters) {
    // function body
};

Step 4: Re-export the module.

You have to re-export the module for the overriden functionalities to take effect.

module.exports = newMod;

Now, you may use the variable to the module,newMod , for calling the function, and the overridden functionality would be executed.

ADVERTISEMENT

Example 1 – Override Function of a Node.js Module

In this example, we shall override readFile() function of Node fs module.

node-js-overriding-function-in-module.js

// include the module whose functions are to be overridden
var fs = require('fs');

// delete the function you would like to override
delete fs['readFile'];

// add new functional with the same name as deleted function
fs.readFile = function(str){
	console.log("The functionality has been overridden.");
	console.log(str);
}

// re-export the module for changes to take effect
module.exports = fs

// you may use the newly overriden function
fs.readFile("sample.txt");

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

~/workspace/nodejs$ node node-js-overriding-function-in-module.js 
Message from newly added function to the module
sample.txt

Overriding readFile() function may not be a great idea, but would suffice for demonstration.

Conclusion

In this Node.js TutorialOverride function of a Node.js module, we have learnt to override functions of a Node.js Module with example Node.js Programs.