Quick Contact

    Node JS Modules

    Node JS is famous because of NPM i.e. Node Package Manager. Modules are small and encapsulated unit which you can reuse and share and easier to maintain.

    For Example-

    You have a big Problem and to solve big problem the first step should be breakdown big problem to small problems and each small problem have a solution and named it as small solutions. Like you can break modules further into more small modules and you have then a small part.

    A small part of Module is easier to maintain, it has less coding, it is easier to share and it is easier to debug. So, Maintenance, debugging and sharing is an important thing. Creating small modules known as modularity. Using a module you can create database, using another module you can write data to database. For Sharing you can publish module to NPM.

    In Node.js it have inbuilt modules like HTTP module, if you want to use it you need to use function called “require” and likewise you have different module in it like FS, Crypto. You can create your own module as well and can use third party module from NPM.

    Let’s look at creating the module

    For this let’s create a file named as “app.js” in which add function. Actually function is the only thing which works. For example, add function is created.

    Node JS Modules

    But this created function within a file cannot be reused by other files. So here what the module is. In a module Function is created differently and import that module into the app.js file by exporting the module files as below-:

    • Add this function to different calc.js module
    • To mention name of file or module you want to include you should always use “require” function
    • To reuse calc function put require in a variable.
    • Node JS Modules
    • Now include this module to use the add function into the file.
    • Node JS Modules
    • Now if you want to use more than one function then how you export them let’s look at following code-:
    • Node JS Modules

    Copyright 1999- Ducat Creative, All rights reserved.