Modules

Modules are libraries of node js. Each single file in node js is considered as a module.

Like in front-end, we include Jquery library and then call jQuery functions, same in Node JS, libraries are included using module and then called. Modules are reusable in nodejs app.

Modules Example

         /* ext.js */
   
    const pi=Math.PI;
    var r=5;
    var a=pi*r*r;
    exports.area=a;
         /* test.js */
   
    const cir=require('./ext');
    console.log(`Area of circle is ${cir.area}`);

Area of circle is 78.53981633974483

npm start

In the example above, ext.js is a module which exports area of a circle with radius 5. In our test.js file, we are including module using require function.


module.exports

module.exports or exports in short is used to export data (string, number, boolean, function, array or object). To export data, use exports (short of modules.exports). There are two types of modules in node js, build-in modules and custom modules.

Build-in modules

Node JS build-in modules includes http module, os modules, path module etc.

To include build-in modules, require function is used.

    const http=require('http');
    const os=require('os');
    const path=require('path');

Custom modules

Custom Modules are external .js files with exports property. Same require function is used to include custom js modules.

         /* ext.js */
   
    const pi=Math.PI;
    var r=5;
    exports.area=pi*r*r;;
    exports.circumference=2*pi*r;

require

require function is used to include external modules in our app. For example, lets says our main file is test.js and module app.js exports a function or any other data type using exports object. See example

Import Module in Node JS

         /* ext.js */
   
    const pi=Math.PI;
    var r=5;
    exports.area=pi*r*r;;
    exports.circumference=2*pi*r;
         /* app.js */
   
    const cir=require('./ext');
    console.log(`Area of circle is ${cir.area}, and circumference is ${cir.circumference}`);

Area of circle is 78.53981633974483 and circumference is 31.41592653589793

npm start

As .js extension is common in both frontend and node, we prefer .js extension for frontend files only. For node application, avoid using .js extension to avoid confusion.