How to create custom module in node JS

What you will learn here about node js

  • How to create custom module in node js
  • How to import custom module in node js

How to create custom module in node js

In node js custom module is created in two ways and those area

  1. default export
  2. named export

Here we will see how to create custom module using default export

In node js module is similar to library which can have one or more functions
1)Below module is created which has one function which is shown below

  1. Create module1.js file
  2. Copy paste following code
  3. Save the changes
function parentFunction()
{
console.log(“Parent Function”);
}
module.exports = parentFunction;

When we exports module means that module we can import is another module.

How to import custom module in node js

Here we will import the module which we had export above

In node JS Module is imported using require function which is show below

1)First we will create another module which will import above module(module1.js)

  1. Create module2.js file
  2. Copy paste following code
  3. Save the changes
const parent = require(“./module1”);
function childFunction()
{
console.log(“Child Function”);
parent();
}
childFunction();


3)Please keep module1.js and module2.js in same directory

4)Now please open node js terminal on your system

5)Please navigate to path where your module1.js and module2.js are kept which is shown below

6)Please execute the following code to run the module2.js

node module2.js

You may also like...