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.
random.js
exports.getRandom = function(){
return Math.floor((Math.random()*10)+1);
};
In the random.js file, there is a function called getRandom() which returns a whole random number between 1 to 10 every time you initiate the main node js file in your browser.
*main.js:-
*
var http = require('http');
var random = require('./random.js');
http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("This is the random number every time you hit the browser. "+random.getRandom());
res.end();
}).listen(8080);
In the above file, you have noticed that I have included two modules inside the require() function. One is built-in module (http) and the other is random.js.
- http module is used to transfer data over the hypertext transfer protocol which means over the web browser.
- random.js is used to print random numbers.
- createServer() object is created using the http so that the response is returned from the server.
- When we call the getRandom() function using the random variable inside the server object, we will get the random numbers from the server each time the request is sent from the browser.
If you hit http://localhost:8000 from your browser, you will see the below output
*This is the random number every time you hit the browser. 3
*
Conclusion:- I wish this tutorial will help you to understand the concept of importing a custom module. If there is any doubt then please leave a comment below.
Top comments (0)