Node.js Modules

Get an overview of benefits of modularity and how to use modules in Node.js.

The benefits of modularity

The general idea behind modules is pretty straightforward and similar to the one behind functions. Instead of writing all the code in one place, thus creating a monolithic application, it’s often better to split the functionalities into smaller, loosely coupled parts. Each part should focus on a specific task, making it far easier to understand and reuse. The general application’s behavior results from the interactions between these building blocks.

These smaller parts are sometimes referred to as components in other environments. In Node, they are called modules and can come under different forms. According to the general definition of a module, it is anything that can be loaded using Node’s require() function. The Node.js platform adheres to the CommonJS module format.

Creating a module

The simplest form of the module is a single JavaScript file, containing special commands to export specific pieces of code. The rest of the code is private to the module and won’t be visible outside of it.

For example, a greetings.js module could contain the following code.

Get hands-on with 1400+ tech skills courses.