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:

  • Local/File-based modules: It define the Node modules within a file in our application and is used within our application.
  • Core modules: The core modules are inbuilt modules in Node.js. These modules provide sufficient functionality so that external module designers can add in their own functionality that can be used while developing Node applications. The core modules include path, file system, os, util, and a few others.
  • Third-party modules: Third-party modules are the external Node modules. These are the third-party Node modules developed by Node developers that are made available through the Node ecosystem. But we need a package manager that maintains all the modules so that they can be accessed with ease. This is where NPM comes into the picture.

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.

  • Creating a Node.js module (rectange.js):
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  • Using the Node module in your application (module.js):
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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");
        });
    };

    chevron_right

    
    

  • Initializing the main file (index.js):
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.