Contents
Node.js Modules
Modules are a fundamental part of Node.js, allowing you to organize your code into reusable pieces. Node.js comes with several built-in core modules, but you can also create your own custom modules to encapsulate specific functionality.
Core Modules in Node.js
Node.js provides a set of core modules that are included in every Node.js installation. These modules are built-in and can be used without needing to install anything additional. Here are some of the most commonly used core modules:
- 1. fs (File System Module)
- The
fs
module provides an API for interacting with the file system, allowing you to read from and write to files. - Example:
- The
const fs = require('fs');
// Reading a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Writing to a file asynchronously
fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File has been saved!');
});
2. path (Path Module)
- The
path
module provides utilities for working with file and directory paths. It helps in handling and transforming file paths in a platform-independent way. - Example:
- The
const path = require('path');
// Join paths
const filePath = path.join(__dirname, 'example.txt');
console.log(filePath);
// Get the file extension
const ext = path.extname('example.txt');
console.log(ext);
3. http (HTTP Module)
- The
http
module allows you to create an HTTP server and handle requests and responses. It’s the foundation for building web servers and RESTful APIs in Node.js. - Example:
- The
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
4. os (Operating System Module)
- The
os
module provides utilities for interacting with the operating system, such as getting information about the CPU, memory, and more. - Example:
- The
const os = require('os');
console.log('OS Platform:', os.platform());
console.log('CPU Architecture:', os.arch());
console.log('Total Memory:', os.totalmem());
5. url (URL Module)
- The
url
module provides utilities for URL resolution and parsing. - Example:
- The
const url = require('url');
const myUrl = new URL('https://www.example.com/path?name=Node.js');
console.log(myUrl.hostname); // 'www.example.com'
console.log(myUrl.pathname); // '/path'
console.log(myUrl.searchParams.get('name')); // 'Node.js'
Creating and Exporting Custom Modules
In Node.js, you can create custom modules to encapsulate functionality and reuse it across different parts of your application.
Step 1: Create a Custom Module
Let’s create a simple module that performs basic arithmetic operations.
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = {
add,
subtract,
};
Step 2: Export the Module
In the math.js
file, we use module.exports
to export the functions so they can be used in other files.
Using require to Import Modules
To use the functions from the math.js
module in another file, you can import the module using require
.
Example:
// app.js
const math = require('./math');
const sum = math.add(5, 3);
const difference = math.subtract(5, 3);
console.log('Sum:', sum); // Output: Sum: 8
console.log('Difference:', difference); // Output: Difference: 2
In this example, require('./math')
imports the math.js
module, and you can then use the add
and subtract
functions in the app.js
file.
Understanding module.exports and exports
In Node.js, every file is treated as a separate module. The module.exports
object is the object that is returned when a module is require
d. You can assign anything to module.exports
to make it available outside the module.
module.exports
: The object that is actually returned as the result of arequire
call.exports
: A shorthand reference tomodule.exports
. By default,exports
is a reference tomodule.exports
, but you can’t reassignexports
directly (doing so will break the reference).
Example:
// math.js
// Using module.exports to export an object
module.exports = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
};
// Equivalent using exports (but without reassignment)
exports.add = function (a, b) {
return a + b;
};
exports.subtract = function (a, b) {
return a - b;
};
Important Note:
// This will break the module.exports reference
exports = {
multiply(a, b) {
return a * b;
},
};
The above code won’t work because exports
is no longer a reference to module.exports
. If you want to assign an object or function directly, use module.exports
.
Conclusion
Node.js modules are a key concept for organizing your code and reusing functionality across your application. Understanding core modules, creating custom modules, and using require
to import them are foundational skills in Node.js development. Additionally, grasping the difference between module.exports
and exports
helps you avoid common pitfalls and write cleaner, more modular code.
Related Chapters
- What is Node.js?
- Setting Up the Development Environment
- Understanding the Basics
- Node.js Modules
- Working with the File System
- Node.js Package Manager (npm)
- Asynchronous Programming in Node.js
- Building a Web Server with Node.js
- Introduction to Express.js
- Working with Databases
- Authentication and Security
- RESTful APIs with Node.js
- Testing in Node.js
- Planning the Project
- Developing the Backend with Node.js
- Developing the Frontend
- Deployment