Node.js comes with a rich set of built-in modules that provide essential functionality for various tasks. These core modules allow developers to interact with the file system, manage URLs, create HTTP servers, and handle file paths efficiently. In this chapter, we’ll explore some of the most commonly used core modules: fs
(File System), url
, http
, and path
.
Working with the fs
Module (File System)
The fs
module in Node.js provides an API for interacting with the file system. It allows you to perform tasks such as reading, writing, and deleting files, as well as working with directories.
Reading Files: You can read files using the fs.readFile
method, which is asynchronous and non-blocking.
const fs = require('fs');
fs.readFile('example.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log('File content:', data);
});
In this example, fs.readFile
reads the content of example.txt
and prints it to the console. The callback function is triggered once the file is read.
Writing Files: To write data to a file, use the fs.writeFile
method.
const fs = require('fs');
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File has been written');
});
This example writes “Hello, Node.js!” to output.txt
. If the file doesn’t exist, it will be created.
Other Common Operations:
fs.rename
to rename files.fs.unlink
to delete files.fs.mkdir
andfs.rmdir
to create and remove directories.
The fs
module also provides synchronous versions of these methods, but they are generally avoided in production environments due to their blocking nature.
Handling URLs and Query Strings with the url
Module
The url
module in Node.js is used to parse and manipulate URLs. This is particularly useful when working with web servers or any application that needs to process URLs.
Parsing URLs: The url.parse
method breaks down a URL into its components, such as protocol, hostname, path, and query string.
const url = require('url');
const myUrl = new URL('https://example.com:8080/path/name?query=string#hash');
console.log('Protocol:', myUrl.protocol);
console.log('Host:', myUrl.host);
console.log('Pathname:', myUrl.pathname);
console.log('Search Params:', myUrl.searchParams);
In this example, url.parse
extracts different parts of the URL for easy access and manipulation.
Handling Query Strings: The url
module also allows you to work with query strings, converting them into JavaScript objects for easy access.
const querystring = require('querystring');
const qs = querystring.parse('name=John&age=30');
console.log(qs.name); // Output: John
console.log(qs.age); // Output: 30
This code snippet demonstrates how to parse a query string into an object, making it easier to work with the parameters.
Creating HTTP Servers with the http
Module
One of the most powerful features of Node.js is its ability to create HTTP servers using the http
module. This module allows you to set up web servers that can handle requests and send responses.
Basic HTTP Server: Here’s a simple example of creating an HTTP server with Node.js:
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/');
});
In this example, an HTTP server is created that listens on port 3000. When a request is received, the server responds with “Hello, World!”.
Handling Different Routes: You can enhance your server by handling different routes and methods.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url = = = '/' && req.method = = = 'GET') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Welcome to the Home Page</h1>');
} else if (req.url = = = '/about' && req.method = = = 'GET') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>About Us</h1>');
} else {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
This server handles requests for different routes (/
and /about
) and responds with appropriate content.
Using the path
Module for File Paths
The path
module provides utilities for working with file and directory paths. It helps in constructing file paths, normalizing paths, and more.
Joining Paths: The path.join
method is used to concatenate different parts of a file path.
const path = require('path');
const filePath = path.join(__dirname, 'folder', 'file.txt');
console.log(filePath);
This code combines __dirname
(which represents the current directory) with ‘folder’ and ‘file.txt’ to create a full path.
Getting File Information: You can use methods like path.basename
and path.extname
to get information about a file path.
const path = require('path');
const filePath = '/folder/subfolder/file.txt';
console.log('Base name:', path.basename(filePath)); // Output: file.txt
console.log('Extension:', path.extname(filePath)); // Output: .txt
These methods extract the base name (file name with extension) and the extension from a file path.
Conclusion
The core modules and APIs in Node.js are powerful tools that simplify tasks such as file manipulation, URL handling, server creation, and path management. Understanding how to use these modules effectively is crucial for building robust and efficient Node.js applications. As you continue exploring these modules, you’ll find that they provide a solid foundation for developing a wide range of server-side applications.
#CoreModules, #Nodejs, #fsModule, #FileSystem, #urlModule, #QueryStrings, #httpModule, #HTTPServer, #pathModule, #FilePaths, #BackendDevelopment, #WebDevelopment