Modules in Node.js
A Node.js module is a reusable piece of JavaScript code that can expose functions, objects, classes, or values for use in another Node.js file.
Modules help you split a Node.js application into smaller files instead of writing all code in one large program. In this tutorial, we will learn the main types of Node.js modules, how to include a module with require(), how to use a module function, and how local and third-party modules fit into a Node.js project.

What is a Node.js module?
In Node.js, every file can be treated as a module. A module can keep its own variables and functions private, and it can expose selected parts of its code using exports. Another file can then load the module and use the exported functionality.
Node.js supports the traditional CommonJS module system, where modules are loaded using require(). Modern Node.js also supports ECMAScript modules, usually written with import and export. This tutorial focuses mainly on CommonJS because the existing examples use require(), which is still widely seen in Node.js applications.
For current reference, you may also check the official Node.js Modules documentation and Node.js Packages documentation.
Types of modules in Node.js
There are three common types of modules in Node.js based on where they come from and how they are loaded.
Built-in Node.js modules
Built-in modules are included with the Node.js installation. You do not need to install them separately. Examples include http, fs, path, url, events, and os.
These modules are commonly used for server creation, file handling, path manipulation, event handling, and operating system information.
const path = require('path');
const filePath = path.join('users', 'admin', 'report.txt');
console.log(filePath);
Some built-in modules may also be loaded with the node: prefix. This makes it clear that the module is provided by Node.js itself.
const fs = require('node:fs');
Reference to the list of Node.js Built-in Modules.
User defined Node.js modules
User defined modules are modules created by the developer inside the same project. They are also called local modules. A local module is useful when you want to move reusable logic into a separate file.
For example, you can keep calculator functions in one file and import them into another file where they are needed.
calculator.js
function add(a, b) {
return a + b;
}
module.exports = add;
app.js
const add = require('./calculator');
console.log(add(10, 5));
15
In the above example, calculator.js exports the add() function. The app.js file imports it using a relative path.
We shall learn more in detail about user defined modules in the Node.js User Defined Modules section.
- Create a Node.js module
- Extend a Node.js module
Third party Node.js modules from npm
Third party modules are packages created by other developers and published to npm. They are installed into a project using npm and are usually stored in the node_modules directory.
For example, if a package named dayjs is installed in a project, it can be loaded by its package name.
npm install dayjs
const dayjs = require('dayjs');
console.log(dayjs().format('YYYY-MM-DD'));
Third party modules are useful when a reliable package already solves a common problem, such as date formatting, validation, logging, database access, or API communication.
- Install a Node.js module using NPM
- Extend a Node.js module
- Publish a Node.js module to Github using NPM
Include a module in Node.js using require()
Including a module in the Node.js files allows us to use the functions exposed by the module.
Syntax to include a CommonJS module in Node.js
Following is the syntax to include a module in a Node.js file.
var http = require('<module_name>');
The value returned by require() is assigned to a variable. You can then use that variable to access the functions, objects, or properties exported by the module.
Example to include the http module in Node.js
To include ‘http’ module in a Node.js file, we need to write the below require statement before using the http module.
var http = require('http');
Use a function from a Node.js module
Once you have included a module by assigning it to a variable, the functions in the module could be accessed through the variable.
In the above module section, an example for including http module is provided. Now we shall use a function of http module called createServer() to demonstrate on how to use a function of a module.
example.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Node.js says Hello!');
res.end();
}).listen(8080);
The function creates an HTTP Server that responds with ‘Node.js says Hello!’ when an http request is made to port 8080.
Save the file as example.js and run it from the terminal.
node example.js
Then open http://localhost:8080 in a browser. The server sends a plain text response from the callback function passed to http.createServer().
How Node.js resolves modules loaded with require()
When you call require(), Node.js checks the module name or path and decides where to load the module from.
- Built-in module name:
require('http')loads the built-in HTTP module. - Relative file path:
require('./calculator')loads a local file from the current project. - Package name:
require('express')looks for an installed third-party package innode_modules.
For local files, use ./ or ../ in the path. Without a relative path, Node.js treats the value as a built-in module name or an installed package name.
Export one or more values from a Node.js module
A module must export a value before another file can use it. In CommonJS, this is done with module.exports or exports.
Export a single function from a Node.js module
function greet(name) {
return 'Hello ' + name;
}
module.exports = greet;
Export multiple functions from a Node.js module
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add: add,
subtract: subtract
};
When multiple values are exported as an object, the importing file can access each exported function by property name.
const math = require('./math');
console.log(math.add(8, 2));
console.log(math.subtract(8, 2));
10
6
CommonJS modules and ES modules in Node.js
Many Node.js tutorials and older projects use CommonJS syntax with require() and module.exports. ES modules use import and export. Both module systems are supported in Node.js, but they have different rules for file extensions, package settings, and loading behavior.
CommonJS example:
const http = require('http');
module.exports = myFunction;
ES module example:
import http from 'node:http';
export default myFunction;
For beginners, it is better to avoid mixing the two styles in the same file. Use the style already used by your project, or follow the requirements of the package you are working with.
Common mistakes while working with Node.js modules
- Missing relative path: Use
require('./file')for a local file, notrequire('file'). - Forgetting to export: A function must be exported before another file can import and use it.
- Wrong file location: Check that the path in
require()matches the actual file location. - Mixing module systems without configuration: Do not mix
require()andimportunless you understand the project configuration. - Assuming npm packages are built in: Third party modules must be installed before they can be required.
Node.js modules quick reference
| Module type | Example | How it is loaded | Typical use |
|---|---|---|---|
| Built-in module | http, fs, path | require('http') | Use features provided by Node.js |
| User defined module | ./calculator | require('./calculator') | Reuse code from another file in the same project |
| Third party module | express, dayjs | require('package-name') | Use an installed npm package |
FAQ on Node.js modules
What is a module in Node.js?
A module in Node.js is a reusable file or package that can export code and be loaded by another file. It may contain functions, objects, classes, constants, or complete features.
How do you import a module in Node.js?
In CommonJS, you import a module using require(). For example, const http = require('http'); loads the built-in HTTP module. In ES modules, you use import syntax.
What is the difference between built-in and third-party Node.js modules?
Built-in modules come with Node.js and can be used without installation. Third-party modules are installed from npm or another package source before they can be used in a project.
Why do local Node.js modules use ./ in require()?
The ./ tells Node.js to load a file from the current directory. Without ./, Node.js looks for a built-in module or an installed package with that name.
Can Node.js use both require and import?
Yes, Node.js supports both CommonJS and ES modules, but they follow different rules. A project should use the module style that matches its configuration and dependencies.
Editorial QA checklist for this Node.js modules tutorial
- Confirm that examples using
require()are clearly described as CommonJS examples. - Check that local module examples use relative paths such as
./calculator. - Verify that output-only code blocks use the
outputclass. - Keep built-in, user defined, and third-party Node.js modules explained separately.
- Make sure any future npm package example includes an installation step before using
require('package-name').
Conclusion
In this Node.js Tutorial, we have learnt about Node.js Modules, how to include them in a Node.js file, and how to use a function of a Node.js Module.
TutorialKart.com