What is node js module?
In node js module are JavaScript libraries, or set of functions you want include in your application. Also, each module can be placed in a separate.js file under separate folder. Node js module make your application more structured.
In this tutorial, first we are going to create Loacl modules and then Consume and Export Modules.
Local modules created locally in application but in other file, you can also distributed it to others by using Node Package Manager.
REQUIRE MODULE
Require function are used to include modules in your application. In following code, we include add module in the application and if module is in other location then you need to set path of your module.
inside index.js write fallowing code
const add = require('./add.js');
In above example code our path is ‘./add.js’ inside require function. The ’.’ Is for root folder of application.
EXPORTS MODULE
Exports are used to create own modules. It allows to export own functions and objects.
Create app.js in same location where is your index.js and write fallowing code inside app.js
module.exports = function add(one,two){
return one + two;
}
In above code export is an object. It can expose function, object, function as a class or whatever assign to exports, we expose function in this example.
Now we can use our add function in our add.js file like following code
console.log(add(2,5));
RUN CODE
Run index.js file by using the fallowing command in terminal.
node index.js
The output of code is given below:
LOAD MODULE FROM OTHER FOLDER
Till now we are export module from same location, but if our module is inside other folder i.e named “mod” folder then we need to give full path inside require function then our code inside index.js look like:
const add = require('./mod/add.js');
and rest part of the code will reaming same.
Hope you like the article! feel free to share the feedback, brickbats, and concerns in the comment section below.
0 Comment(s)