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

Node.js Creating Modules

Built-in modules contain most of the necessary functions. Sometimes, when implementing a Node.js application for a specific case, it may be necessary to retain the business logic separately. In this case, you will create a Node.js module that includes all the necessary functions.

In this Node.js tutorial, we will learn how to create Node.js modules and include them in Node.js files with examples.

Create a Node.js module

Node.js modules are .js files that have one or more functions.

The syntax for defining functions in Node.js modules is as follows:

exports.<function_name> = function (argument_1, argument_2, .. argument_N) {  /** function body */ });

exports –This is a keyword that tells Node.js that the feature is available outside the module.

Calculator - Node.js Module Example

Below is an example where we create a Calculator Node.js module with addition, subtraction, and multiplication functions and use the Calculator module in another Node.js file.

// Returns the sum of two numbers
exports.add = function (a, b) { 
    return a+b; 
 });  
 
// Returns the difference between two numbers
exports.subtract = function (a, b) { 
    return a-b; 
 });  
 
// Returns the product of two numbers
exports.multiply = function (a, b) { 
    return a*b; 
 });
var calculator = require('./calculator'; 
 
var a=10, b=5; 
 
console.log("Addition : "+calculator.add(a,b)); 
console.log("Subtraction : "+calculator.subtract(a,b)); 
console.log("Multiplication : "+calculator.multiply(a,b));
$ node moduleExample.js 
Addition : 15
Subtraction : 5
Multiplication : 50

Conclusion:

In this Node.js tutorial, we learned how to create Node.js modules and include the modules in another Node.js file through examples.