Open In App

How to use External Modules and NPM in a project ?

Need for External Modules: For a large JavaScript application, it becomes difficult and messy to write the whole code in just one JavaScript file. This is where CommonJS comes into the picture and this CommonJS format defines a module format that can be used up for breaking your JS application into multiple files. Node.js adopts this CommonJS format for organizing our JS application into multiple files. Within this Node.js application, we have the module.exports property which is used to determine the export from the current module. 
Types of Node modules: Module in Node.js is a simple or complex functionality organized into single or multiple JS files which can be used again throughout the Node.js application. There are three types of Node.js modules: 
 

NPM (Node Package Manager): NPM is the default package manager for JavaScript runtime environment in Node.js. The Node.js Package Manager (npm) is the default and most popular package manager in Node.js ecosystem that is primarily used to install and maintain external modules in Node.js application. Users can basically install the node modules needed for their application using npm. 
How to export Modules ? 
First, initialize a node.js application by typing in npm init in the command prompt/terminal (make sure you are present in the current project folder). It will create a package.json file.
Use the following syntax to add a module in Node.js project. 
Syntax: 
 



var module = require("module_name");

Creating own modules and using it: First, initialize node in a directory by typing npm init in the command prompt/terminal. 
 




module.exports = (length, breadth, callback) => {
    if (length <= 0 || breadth <= 0)
        setTimeout(() => callback(new Error(
                "Dimensions cannot be negative: length = "
                + length + ", and breadth = "
                + breadth), null), 5000);
    else
        setTimeout(() => callback(null, {
                Perimeter: () => (2*(length+breadth)),
                 Area:() => (length*breadth) }), 5000);
}




var rect = require('./rectangle');
module.exports.Rect = function Rect(l, b) {
    rect(l, b, (err, rectangle) => {
        if (err)
            console.log("There is an ERROR!!: ", err.message);
        else {
            console.log("Area of rectangle with dimensions length = "
                + l + " and breadth = " + b + " : " + rectangle.Area());
             
            console.log("Perimeter of the rectangle with dimensions length = "
                 + l + " and breadth = " + b + " : " + rectangle.Perimeter());
        }
     console.log("\n\n");
    });
};




var rect = require("./module");
rect.Rect(5, 2);
rect.Rect(-1, 0);
rect.Rect(12, 4);
rect.Rect(8, 6);
rect.Rect(3, 4);

Output: 
 



 


Article Tags :