Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Node.js Modules and CommonJS

Node.js Modules and CommonJS

Node.js follows the CommonJS module system, which provides a way to organize code into reusable modules. This module system is essential for structuring complex applications and managing dependencies. Here are the key concepts related to Node.js modules and CommonJS:

Creating Modules:

1. Creating a Module:

To create a module, you simply create a JavaScript file. For example, you can create a file named myModule.js.

// myModule.js
let myVariable = "This is my module.";

function myFunction() {
  console.log("This is my function.");
}

module.exports = {
  myVariable,
  myFunction
};
 

In this example, we're exporting an object containing a variable and a function.

2. Exporting Functions or Variables:

To make functions or variables available to other parts of your application, you need to use module.exports.

module.exports = {
  myVariable,
  myFunction
};
 

Using Modules:

1. Importing Modules:

In order to use a module in another file, you need to require it using require().

const myModule = require('./myModule');

console.log(myModule.myVariable);
myModule.myFunction();
 In this example, we're importing the myModule.js file using require(). This gives us access to the exported variables and functions.

 

2. Accessing Exported Elements:

When you import a module, you can access its exported elements using dot notation.

const myVariable = myModule.myVariable;
myModule.myFunction();
 

You can also use destructuring to directly access the exported elements:

const { myVariable, myFunction } = require('./myModule');
 

Core Modules and npm Modules:

1. Core Modules:

Node.js provides a set of core modules that are built into the runtime environment. These can be used without the need for installation. For example, modules like fs (File System), http (HTTP Server), and path (File Path) are core modules.

const fs = require('fs');
 

2. npm Modules:

In addition to core modules, you can use external modules available on npm (Node Package Manager). To use an npm module, you first need to install it using npm install.

npm install my-npm-module
 

Then, you can require and use the module in your code.

const myNpmModule = require('my-npm-module');
 

Summary:

  • Node.js follows the CommonJS module system for organizing code into reusable modules.
  • Modules are created by creating separate JavaScript files and using module.exports to expose functions or variables.
  • Modules can be imported using require() in other parts of the application.
  • Core modules are built-in modules provided by Node.js, while npm modules are external libraries that can be installed and used.
  • Understanding modules is essential for building large and maintainable Node.js applications with proper code organization and dependency management.