Extend or add functions to Node.js module

Extend or add functions to Node.js module – There could be scenarios where you would like to improve the functionalities of existing modules or add a new functionality by yourself.

In this tutorial, we shall learn to add new functionalities to an existing module.

To add a new function to a Node.js module, following is a step by step guide.

1. Include the module

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

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

We have retrieved the module to a variable.

2. Add function to the module variable

Using variable to the module, newMod , add a new function to it using following syntax.

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

You may add as many number of new functions to the module as per your requirement.
Any modifications to the module variable does not affect the actual module in its original form.

3. Re-export the module

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

</>
Copy
  module.exports = newMod;

Now, you may use the variable to the module, newMod , for calling new functionalities added.

Example : Extend or add functions to Node.js module

In this example we shall add a new function, printMessage() to Node fs module.

node-js-extending-module.js

</>
Copy
// include the module that you like extend
var fs = require('fs');

// add a new function, printMessage(), to the module
fs.printMessage = function(str){
	console.log("Message from newly added function to the module");
	console.log(str);
}

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

// you may use the newly added function
fs.printMessage("Success");

Output

~/workspace/nodejs$ node node-js-extending-module.js 
Message from newly added function to the module
Success

The printMessage() function may not be of great use, but would suffice for demonstration.

Conclusion

In this Node.js TutorialExtend or add functions to Node.js module, we have learnt to add new functionalities to an existing module.