In Node.JS, Every JavaScript file is its own module and So far we have been loading module using the require function.

What is Require function?

The require function is the part of common JavaScript module. But it is only half part and the other half of the part is module.exports or method that we use to export the data and functionality from a module.

You can visit official website at https://nodejs.org/en/knowledge/getting-started/what-is-require.

Lets take an example for better understanding so lets create a file namely myModule.js

myModule.js
module.export = "kiran";

then create other file app.js to import the value from myModule.js file.

app.js
const name = require("./myModule");

console.log("My name is ", name);


Output-

(Figure 1: export data)

The require function that we invoked in app.js file will export the value of module.exports from our other file i.e. myModule.js

Let take an other example, further I am going to go ahead and create a variable called counter and then I will create a function for incrementing the counter & as well as for decrementing the counter inside our myModule1.js file.

myModule1.js

let counter = 0;
const inc = () => counter++;
const dec = () => counter--;

const getcount = () => counter;
module.exports = {
  inc,
  dec,
  getcount
};

then create other file app1.js to import the functions that are inc(), dec(), getCount() from myModule1.js file.

app1.js
const functions = require("./myModule1");

functions.inc();
let counterCurrentValue = functions.getcount();
console.log("Incremented counter value", counterCurrentValue);


functions.inc();
counterCurrentValue = functions.getcount();
console.log("Incremented counter value", counterCurrentValue);

functions.dec();
counterCurrentValue = functions.getcount();
console.log("Decremented counter value", counterCurrentValue);

Output:

(Figure 2: Export functions)

So as we can see in our above examples the Node.js module system allows us to separate our functionality into separate files. we consume/use that functionality with there require function and what get return by the require function is what we exported with the module.exports function.

Leave a Reply

Your email address will not be published. Required fields are marked *