How to override functions of module in Node.js ?
Overriding means not change the original definition of any object or module but changing its behavior in the current scenario (where it has been imported or inherited). In order to implement overriding, we are going to override the function of ‘url‘, the in-built module of nodeJS. Let us look at the steps involved in overriding a module:
- First of all, require the module which we want to override.
const url = require('url')
- Then delete the function of the module which we want to override. Here we would override the format() function of ‘url‘ module
delete url['format']
- Now add the function with the same name ‘format‘ to provide a new definition to the format() function of the module
url.format = function(params...) {
// statement(s)
}
- Now re-export the ‘url‘ module for changes to take effect
module.exports = url
Let us walk through step by step to implement the full working code:
Step 1: Create an “app.js” file and initialize your project with npm.
npm init
The project structure would look like this:
Project/File structure
Step 2: Now let us code the “app.js” file. In it, we follow all the steps mentioned above for overriding a module. After those steps, you would have successfully overridden the format() function of ‘url’ module. Find the full working code below in which the behaviour of format() function before overriding and after it has been shown.
app.js
const url = require( "url" );
delete url[ "format" ];
url.format = function (str) {
return "Sorry!! I don't know how to format the url" ;
};
module.exports = url;
|
Step 3: Run your node app using the following command.
node app.js
Output:
output in console
Last Updated :
10 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...