1. Built-in Modules in Node.js

Node.js comes with several powerful built-in modules that make server-side development efficient and straightforward. These modules allow developers to handle essential operations like file manipulation, working with system information, managing HTTP requests, and more. In this guide, we’ll explore four key modules: Path, File System (fs), OS, and HTTP, highlighting their features and practical usage.


2. Path Module

The path module in Node.js provides utilities for working with file and directory paths. It helps normalize paths, join segments, resolve relative paths, and more, making it essential for file handling.

Key Methods

1. path.join()

Combines multiple path segments into one normalized path.

				
					const path = require('path');

const fullPath = path.join(__dirname, 'folder', 'file.txt');
console.log(fullPath); // Outputs the complete path to file.txt

				
			

2. path.resolve()

Resolves a sequence of paths into an absolute path.

				
					const absolutePath = path.resolve('folder', 'file.txt');
console.log(absolutePath); // Outputs an absolute path based on the current working directory

				
			

3. path.basename()

Returns the last portion of a path (e.g., file name).

				
					const fileName = path.basename('/folder/file.txt');
console.log(fileName); // Outputs: file.txt

				
			

4. path.extname()

Returns the file extension from a path.

				
					const fileExt = path.extname('file.txt');
console.log(fileExt); // Outputs: .txt

				
			


3. File System (fs) Module

The fs module provides functions to interact with the file system, such as reading, writing, and deleting files. It supports both synchronous and asynchronous operations, offering flexibility in handling files.

Key Methods

1. fs.readFile()

Reads the content of a file asynchronously.

				
					const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data); // Outputs the content of example.txt
});

				
			

2. fs.writeFile()

Writes data to a file, creating it if it doesn’t exist.

				
					fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
  if (err) throw err;
  console.log('File has been written!');
});

				
			

3. fs.appendFile()

Appends data to an existing file.

				
					fs.appendFile('output.txt', '\nAppending new content!', (err) => {
  if (err) throw err;
  console.log('Content appended!');
});

				
			

4. fs.unlink()

Deletes a file asynchronously.

				
					fs.unlink('output.txt', (err) => {
  if (err) throw err;
  console.log('File deleted!');
});

				
			


4. OS Module

The os module provides information about the operating system, including CPU details, memory usage, and system uptime. It's useful for gathering system-specific information.

Key Methods

1. os.platform()

Returns the platform of the operating system.

				
					const os = require('os');
console.log(os.platform()); // Outputs: win32, linux, darwin, etc.

				
			

2. os.cpus()

Returns an array containing information about each logical CPU core.Returns an array containing information about each logical CPU core.

				
					console.log(os.cpus()); // Outputs details about CPU cores

				
			

3. os.freemem() and os.totalmem()

Provides the free and total memory available in the system.

				
					console.log(`Free Memory: ${os.freemem()} bytes`);
console.log(`Total Memory: ${os.totalmem()} bytes`);

				
			

4. os.uptime()

Returns the system uptime in seconds.

				
					console.log(`System Uptime: ${os.uptime()} seconds`);

				
			


5. HTTP Module

The http module is essential for creating web servers and handling HTTP requests and responses. It allows you to build robust server-side applications that can handle incoming network requests.

Creating a Simple HTTP Server

				
					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/');
});

				
			

Handling Different Routes

				
					const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Welcome to the homepage!');
  } else if (req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('About us page');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('404 Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

				
			


6. Conclusion

Node.js built-in modules—Path, File System (fs), OS, and HTTP—provide essential tools for developing scalable, efficient server-side applications. These modules help with file handling, system information, and creating web servers, making them integral to any Node.js project. By mastering these modules, developers can streamline their coding process, ensuring robust and maintainable applications. This content is unique, SEO-optimized, and designed to help your course page rank higher while offering valuable information to learners.

×