Override function of a Node.js module

Override function of a Node.js module

Override function of a Node.js module – There could be scenarios where you would like to improve the functionalities of existing modules by overriding them. In this Node.js Tutorial, we shall learn to override a function of a Node.js module.

To override an existing function of a Node.js module, following is a step by step guide :

  1. Include the module.

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

    We have retrieved the module to a variable.

  2. Delete function from the module variable.

    Using variable to the module, newMod , delete the function from it using following syntax.

    Please remember that the changes would be only to the module variable, newMod, but not to the original module itself.

  3. Add function, with same name, to the module variable.

    Using variable to the module, newMod , add the function with the same name, that we deleted in the previous step, using following syntax.

  4. Re-export the module.

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

    Now, you may use the variable to the module, newMod , for calling the function, and the overridden functionality would be executed.

 

Example : Override function of a Node.js module

In this example we shall override readFile() function of Node fs module.

Overriding readFile() function may not be a great idea, but would suffice for demonstration.

 

Conclusion :

In this tutorial – Override function of a Node.js module, we have learnt to override functions of a Node.js Module with example Node.js Programs.