How to Create a Node.js Module

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

Create a Node.js Module

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

Following is the syntax to define a function in Node.js module :

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

exports – It is a keyword which tells Node.js that the function is available outside the module.

 

Calculator – Example of a 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.

 

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.