Open In App

How to override functions of module in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Requiring the in-built url module
// to override
const url = require("url");
  
// The default behaviour of format()
// function of url
console.log(url.format("http://localhost:3000/"));
  
// Deleting the format function of url
delete url["format"];
  
// Adding new function to url with same
// name so that it would override
url.format = function (str) {
  return "Sorry!! I don't know how to format the url";
};
  
// Re-exporting the module for changes
// to take effect
module.exports = url;
  
// The new behaviour of export() function
// of url module
console.log(url.format("http://localhost:3000/"));


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
Previous
Next
Share your thoughts in the comments
Similar Reads