Extend or add functions to Node.js module

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 Node.js 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.

    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.

    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.

    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.

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

 

Conclusion :

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