Premium lesson

The CommonJS Module System in Node.js

Node.js·4 min read·Jan 1, 2025

In Node.js, a module is a file that encapsulates related functionality, such as variables, functions, or classes, that can be easily shared and reused into other parts of a project.

Modules help organize code into manageable and maintainable units, promoting code reusability and separation of concerns.

In practice, a module is a .js, .cjs, or .mjs file whose content is private by default, which means that the variables, functions, and classes it contains are inaccessible by the others files composing the application unless they are explicitly exported.

The types of Node.js modules

In Node.js, modules can be of three types: built-in, local, and third-party.

Built-in modules

Built-in modules, also called core modules, are a set of modules that come prepackaged with every Node.js distribution.

They provide essential functionality for interacting with the filesystem, handling networking, performing cryptography, and more.

Local modules

Local modules are created by developers to organize their code into reusable and maintainable units.

These modules are specific to a particular project and are usually stored in separate files within the project directory.

Developers can create their own modules by defining functions, classes, or variables in one file and then exporting them for use in other files.

Third-party modules

Third-party modules are modules created by external developers or the open-source community.

These modules are not part of the Node.js core, and developers can use package managers like npm to install and manage them.

Third-party modules provide a wide range of additional functionalities, such as HTTP frameworks, database connectors, utility libraries, and more.

Importing CommonJS modules

The CommonJS module system is the original way to package JavaScript code for Node.js.

To import a CommonJS module into another file, you can use the global require function:

icon light bulb key

Unlock the Build CLI Apps in JavaScript & Node.js module

Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.

You get immediate access to:

  • 45 focused lessons across JavaScript, Node.js, npm, and Git
  • 17 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module