Open In App

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:

const url = require('url')
delete url['format']
url.format = function(params...) {
    // statement(s)
}
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.




// 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

Article Tags :