Introduction to Modules
Learn to organize code in Node.js using modules, require, and custom module creation.
In Node.js, a module is a reusable block of code that can be imported into other files. Modules are a cornerstone of Node.js, enabling developers to organize applications into smaller, reusable, and maintainable blocks of code. Node.js uses the CommonJS module system, which provides a standard way to define and import modules.
Built-in modules
Node.js comes with several built-in modules that provide core functionality. Examples include:
fs
: For interacting with the file system.http
: For creating HTTP servers.path
: For working with file and directory paths.
These modules add essential capabilities to Node.js applications. We’ll explore them in more detail later in the course as we build and expand our applications.
Using require
to import modules
The require
function lets us import both built-in and custom modules. When we import a module with require
, Node.js looks for it in the following order: