In Node.js, a module is a reusable block of code whose existence does not accidentally impact other code. Each module in Node.js has its own context, which means that the variables, functions, classes, etc., defined in a module are not visible outside of it unless explicitly exported.
Modules in Node.js are essential for organizing and structuring code, promoting code reuse, and separating concerns. They can be either built-in, third-party, or user-defined.
1. Built-in Modules: These are modules provided by Node.js itself, like `fs`, `http`, `path`, etc.
2. Third-party Modules: These are modules created by the community and can be installed using npm (Node Package Manager).
3. User-defined Modules: These are custom modules created by developers for their specific application needs.
To create a module, you simply write a JavaScript file and export the functionalities you want to be available to other files.
// mathOperations.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
In the above example, `mathOperations.js` is a module that exports two functions: `add` and `subtract`.
To use a module in another file, you import it using the `require` function.
// app.js
const math = require('./mathOperations');
const sum = math.add(5, 10);
const difference = math.subtract(10, 5);
console.log(`Sum: ${sum}`); // Sum: 15
console.log(`Difference: ${difference}`); // Difference: 5
Here, the `mathOperations` module is imported into `app.js` and its functions are used to perform arithmetic operations.
Node.js comes with several built-in modules that provide various functionalities. Some commonly used ones are:
1. fs: Provides an API for interacting with the file system.
2. http: Used to create HTTP servers and clients.
3. path: Utilities for working with file and directory paths.
// Using the 'fs' module to read a file
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
These modules are installed via npm. For example, to use the `express` module, you would first install it using npm:
npm install express
Then, you can use it in your application:
// Using the 'express' module
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Modules in Node.js are a powerful way to structure your application, promote code reuse, and keep your code clean and manageable. Whether you are using built-in modules, third-party modules, or creating your own, understanding how to work with modules is essential for any Node.js developer.