Node Modules

Node Modules

Modules In JavaScript

  1. A module is a function or group of similar functions. They are grouped together within a file and contain the code to execute a specific task when called into a larger application.

  2. Advantages Of Using Modules

    • Independent/Self-contained: A module has to be as detached from other dependencies as possible.

    • Specific: A module needs to be able to perform a single or a related group of tasks. The core essence of creating them in the first place is to create separate functionalities. One module, one (kind of) task.

    • Reusable: A module has to be easy to integrate into various kinds of programs to perform its task.

  3. Instead of having all of those unrelated programs together in one module/file, it is a better practice to create several files, or modules, for each of those tasks. In such a case, the modules become dependencies.

  4. Then from the main app or program, you simply import/load the dependencies (i.e the modules you need) and execute them accordingly. As a result, your main app becomes cleaner and more minimal.

  1. Assuming you need to process payments in some other application in the codebase, for example, it becomes very easy to reuse the same functionality. No need to copy and paste or code a new function from scratch

  2. In JavaScript, we use the import and export keywords to share and receive functionalities respectively across different modules.

    • The export keyword is used to make a variable, function, class or object accessible to other modules. In other words, it becomes a public code.

    • The import keyword is used to bring in public code from another module.

Using Modules In Node

  1. To include a module, use the require() function with the name of the module.

  2. When use require it will execute the file inside the module which we are exporting

  3. But if we want to use some part of the code then we need to export it

  4. To include a module, use the require() function with the name of the module.

     console.log(module)
    
     // {
     //   id: ".",
     //   path: "...",
     //   exports: {},--------this is what we are looking for
     //   parent: null,
     //   filename: "...",
     //   loaded: false,
     //   children: [],
     //   paths: [
     //     ...
     //   ],
     // }
    
  5. Node Js uses common js

  6. We need to mention the function/element which we want to be used in other files