What is Node Module System
In this post we will understand the node module system , what is node module ? How node module works ?
In javascript file when we declare a function or a variable that's get added to the global scope, There is a problem in realtime application , in realtime application we ofter split our Javascript code into multiple files.
It is possible we can define two different function with the same name , and both the functions will get added in the global scope and since both the functions are having same name so one function will get override by the latest one .
To avoid this kind of issue and to build reliable and maintainable application we should avoid defining variables and function in the global scope.
Instead we need modularity in our application.
We need to create building blocks where we can define functions and variables so that two variables don't override by another variable defined somewhere else.
Every file in Node Application considered as node module , if you declare a variable or function in a module , that variable and the function will be available only in that file . If you want to access that variable or the function in another file then first we need to make them public by exporting them.
Create a module
In a demo Node application we will have to files one is logger.js
which is a module contains log function and another is app.js
, In this example we will see how we can export the log function and how we can import and use that function in app.js file.
Let's create a reusable Node module which will be responsible to log messages , Create a Javascript file.
logger.js
function log(message){
console.log(message);
}
module.exports.log = log;
Module has a property called exports :{}
anything we add to the exports property will be exported from the module and will be available outside of the module.
Now we are going to use the log function in app.js file.
app.js
const log = require('./logger');
log.log("Some Message");
Now in the command line run command node app.js
sahebsutradhar@Sahebs-MacBook-Pro MEAN % node app.js
Some Message
To load a module we use require() function . This function takes the path of the target module as parameter ,
const log = require('./logger');
There is no need to add .js
after ./logger , Node is smart enough to understand that is a Javascript file . const
, because we do not want to modify the value of the const .module.exports.log = log;
/*
const log = require('./logger');
log = { log: [Function: log] }
*/
module.exports = log;
//assigning log function directly to the exports property
I hope this article is helpful for you , i am very glad to help you thanks for reading