English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Alternative functions for Node.js modules – in someIn cases where you want to improve the functionality of an existing module by rewriting it. In this Node.js tutorial, we will learn how to rewrite the functions of Node.js modules.
To rewrite the existing functions of a Node.js module, please follow the following step-by-step guide:
The first step to override a function in the module is to include the module itself using the require function.
var newMod = require('<module_name>');
We have retrieved the module into the variable.
Use the following syntax to remove the function from the variable in the module newMod.
delete newMod['<function_name>'];
Remember that the changes made are only to the module variable newMod, and not to the original module itself.
In the module newMod, use the following syntax to add a function with the same name as the one deleted in the previous step.
newMod.<function_name> = function(function_parameters) { // function body };
You must reexport the module to make the overridden functionality take effect.
module.exports = newMod;
Now, you can use the variable newMod for the module to call the function, and then execute the overridden functionality.
In this example, we will override the readFile() function of the Node fs module.
The first step to override a function in a module is to use the require function to include the module itself.
// Include the module that you want to override its functionality var fs = require('fs'); // Delete the functionality you want to override delete fs['readFile']; // Add a new function with the same name as the deleted function fs.readFile = function(str){ console.log("The functionality has been overridden."); console.log(str); } // Reexport the module to make the changes take effect module.exports = fs // You can use the new overridden functionality fs.readFile("sample.txt");
Output Result
~/workspace/nodejs$ node node-js-overriding-function-in-module.js
Message from newly added function to the module
sample.txt
It may not be a good idea to rewrite the readFile() function, but it is sufficient for demonstration purposes.
In this tutorial–Rewriting Node.js Module FunctionalityWe have learned to use the example Node.js program to cover the functionality of Node.js modules.