English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

Other NodeJS

Add features to modules in Node.js

Extend or add functions to Node.js modules

Extend or add functions to Node.js modules–inCertainIn this case, you want to improve the functionality of an existing module or add new features yourself. In this Node.js tutorial, we will learn how to add new features to existing modules.

To add a new function to a Node.js module, please follow the following step-by-step guide:

Include the module

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

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

We have retrieved the module into the variable.

Add functionality to module variables

Use the following syntax to add new features to the module variables in the module newMod.

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

You can add as many new features as needed to the module. Any modification to the module variables will not affect the actual module in its original form.

Re-export the module

You must re-export the module to make the new added features take effect.

  module.exports = newMod;

Now, you can use the variables of the module newMod to call the new features added.

Example: Adding Extensions or Functions to Node.js Modules

In this example, we will add a new function printMessage() to the Node fs module.
The first step in extending a module is to include the module itself using the require function.

// Include the module you like to 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 to make the changes take effect
module.exports = fs
 
// You can use the new features added
fs.printMessage("Success");

Output Result

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

The printMessage() function may not be very useful, but it is sufficient for demonstration purposes.

Conclusion:

In this tutorial–Extending or Adding Features to Node.js ModulesWe have learned how to add new features to existing modules.