Create Module in Node.js

Most of the necessary functions are included in the Built-in Modules. Sometimes it is required that, when you are implementing a Node.js application for an use case, you might want to keep your business logic separately. In such cases you create a Node.js module with all the required functions in it.

In this Node.js Tutorial, we shall learn how to create a Node.js module, and include it in Node.js file with an Example.

Create a Node.js Module

How to Create a Node.js Module?

A Node.js Module is a .js file with one or more functions.

The syntax to define a function in Node.js module is

</>
Copy
exports.<function_name> = function (argument_1, argument_2, .. argument_N) {
    /** function body */
};
  • exports – is a keyword which tells Node.js that the function is available outside the module.
  • function_name – is the function name using which we can access this function in other programs.

Calculator – Example Node.js Module

Following is an example where we create a Calculator Node.js Module with functions add, subtract and multiply. And use the Calculator module in another Node.js file.

calculator.js

</>
Copy
// Returns addition of two numbers
exports.add = function (a, b) {
    return a+b;
}; 

// Returns difference of two numbers
exports.subtract = function (a, b) {
    return a-b;
}; 

// Returns product of two numbers
exports.multiply = function (a, b) {
    return a*b;
}; 

moduleExample.js

</>
Copy
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));

Output

$ node moduleExample.js 
Addition : 15
Subtraction : 5
Multiplication : 50

Conclusion

In this Node.js Tutorial, we have learnt how to create a Node.js module, and include the module in another Node.js file with an Example.