Member-only story
How to Import Custom Module in Node JS
Hi friends, in this tutorial, you will learn how to import a custom module in Node JS. Before getting started with the custom module, you must know what the module means in node js and how to include that module before creating any object. A module is nothing but a javascript function or a library.
Also, there are built-in modules and you can directly invoke those modules with the help of require() function by assigning them to a javascript variable. As I already discussed one of the built-in modules ( http) and how to use it. So, I will explain the custom module in a step-by-step process.
Also read, the Node JS HTTP server example
Three steps to import custom module in Node JS
- Create a javascript file where the main node js file is located.
- Declare a function or more than one function in that javascript file.
- Invoke that external JS file in the main node JS file using the required function as shown below.
var random = require('./random.js');
Please note that random.js is assigned to a variable ‘ random ‘. Later on, we will use this random variable to call the functions executed in the random.js file.