Node.js comes with a collection of built-in modules that allow you to interact with various features of the operating system, network, and file system without the need for additional libraries. These modules are part of the Node.js standard library and are automatically available without needing to be installed via NPM. You simply use the require()
function to load them into your project.
Here’s a list of some of the most commonly used built-in modules in Node.js:
1. http
The http
module allows you to create an HTTP server and handle HTTP requests and responses.
Example:
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/');
});
2. fs (File System)
The fs
module provides an API for interacting with the file system, allowing you to read, write, delete, and manipulate files and directories.
Example:
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
fs.writeFile('output.txt', 'Hello, Node.js!', err => {
if (err) throw err;
console.log('File has been saved!');
});
3. path
The path
module provides utilities for working with file and directory paths. It helps you format, resolve, and manipulate paths effectively.
Example:
const path = require('path');
// Join paths
const joinedPath = path.join('/users', 'node', 'docs');
console.log(joinedPath); // Output: /users/node/docs
// Get the file extension
const ext = path.extname('example.txt');
console.log(ext); // Output: .txt
4. os (Operating System)
The os
module provides information about the operating system, such as the hostname, platform, memory usage, and CPU information.
Example:
const os = require('os');
console.log('OS Platform:', os.platform());
console.log('Free Memory:', os.freemem());
console.log('Total Memory:', os.totalmem());
console.log('CPU Info:', os.cpus());
5. events
The events
module provides an EventEmitter class, which is central to event-driven programming in Node.js. It allows you to create and handle custom events.
Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Creating an event listener
emitter.on('greet', () => {
console.log('Hello, Node.js!');
});
// Emitting the event
emitter.emit('greet');
The following code snippet demonstrates how to use the EventEmitter class from the events
module in Node.js to create and emit custom events:
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Creating an event listener
emitter.on('greet', () => {
console.log('Hello, Node.js!');
});
// Emitting the event
emitter.emit('greet');
Here’s a detailed breakdown of each part:
5.1. const EventEmitter = require('events');
- This line imports the
events
module, which is built into Node.js. - The
events
module provides theEventEmitter
class, allowing you to create and manage events and event-driven programming.
5.2. const emitter = new EventEmitter();
- This line creates a new instance of the
EventEmitter
class calledemitter
. - This
emitter
object will be used to create event listeners and emit events.
5.3. Creating an Event Listener: emitter.on('greet', ...)
- The
on()
method is used to register an event listener. It listens for a specific event to occur, and when the event is triggered, the callback function associated with that event is executed. - First Argument (‘greet’): This is the name of the event you want to listen for. In this case, the event is named
'greet'
. - Second Argument (
() => {...}
): This is the callback function that will be executed when the'greet'
event is emitted. Here, it simply logs “Hello, Node.js!” to the console.
5.4 Event Listener Breakdown:
emitter.on('greet', () => {
console.log('Hello, Node.js!');
});
emitter.on()
: Sets up the listener for the'greet'
event.- The callback function (
() => console.log('Hello, Node.js!')
) is stored and will be executed when the'greet'
event is triggered.
5.5. Emitting the Event: emitter.emit('greet')
- The
emit()
method is used to trigger or fire an event. - First Argument (‘greet’): This specifies the event to emit (in this case, the
'greet'
event). - When the
'greet'
event is emitted, Node.js will look for any listeners attached to this event and execute the associated callback function.
5.6 Event Emission Breakdown:
emitter.emit('greet');
emitter.emit()
: This line triggers the'greet'
event.- Since the
'greet'
event has a listener (from the previouson()
call), the callback function is executed, and the message “Hello, Node.js!” is printed to the console.
Full Process Flow:
- Event Listener Creation:
- The event listener for the
'greet'
event is registered usingemitter.on()
. - When this event is triggered, the registered callback will log
"Hello, Node.js!"
.
- Event Emission:
- The event
'greet'
is emitted usingemitter.emit()
. - The event is detected by the
emitter
, and the callback associated with'greet'
is executed. - As a result, “Hello, Node.js!” is printed to the console.
Why Use Event Emitters?
The EventEmitter
class is central to event-driven programming, which is commonly used in Node.js. This pattern allows you to build systems that respond to various events asynchronously. It’s widely used in web servers, where various events like HTTP requests, errors, or data streams can trigger actions.
_________________________________________________
6. url
The url
module helps parse and format URLs. Learn Here
7. crypto
The crypto
module provides cryptographic functionalities in Node.js. Learn Node.js Crypto Here
Example:
8. querystring
The querystring
module is used to parse and stringify URL query strings. Learn Node.js Querystring Module Here
9. stream
The stream
module is used to handle streaming data, which allows for reading and writing files, network communications, and other continuous data exchanges. Streams are used for processing data piece by piece rather than loading an entire resource into memory at once.
Example:
const fs = require('fs');
// Reading a file as a stream
const readStream = fs.createReadStream('example.txt');
readStream.on('data', chunk => {
console.log('Chunk received:', chunk);
});
10. buffer
The buffer
module is used to handle binary data. Buffers are primarily used when dealing with raw binary data, such as reading from or writing to a file or socket.
Example:
const buffer = Buffer.from('Hello, Node.js');
console.log(buffer); // Output: <Buffer 48 65 6c 6c 6f 2c 20 4e 6f 64 65 2e 6a 73>
console.log(buffer.toString()); // Output: Hello, Node.js
11. timers
The timers
module provides functions that deal with time-based operations, such as setting timeouts and intervals.
Example:
setTimeout(() => {
console.log('Timeout executed after 2 seconds');
}, 2000);
setInterval(() => {
console.log('This message is shown every 1 second');
}, 1000);
12. child_process
The child_process
module allows you to spawn and manage child processes. This is useful when you need to execute external commands or scripts from your Node.js program.
Example:
const { exec } = require('child_process');
exec('ls', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
13. zlib
The zlib
module is used for compression and decompression of data, typically using the Gzip or Deflate algorithms.
Example:
const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
const input = fs.createReadStream('input.txt');
const output = fs.createWriteStream('input.txt.gz');
input.pipe(gzip).pipe(output);
14. dns
The dns
module provides an API for performing DNS (Domain Name System) lookups and domain name resolution.
Example:
const dns = require('dns');
dns.lookup('example.com', (err, addresses, family) => {
console.log('IP address:', addresses);
});
Conclusion
Node.js comes packed with powerful built-in modules, making it a flexible and efficient environment for developing various types of applications. Each module serves different purposes, from creating web servers to performing file system operations, handling cryptography, and more. These built-in modules form the backbone of Node.js applications and can be combined to create robust, scalable solutions for a variety of use cases.