Node Modules
Published by
sanya sanya
Node modules
, also known as npm modules
, are packages or libraries of reusable code that can be easily integrated into Node.js applications
. They are created and shared by developers worldwide to provide specific functionality or solve common programming problems.
Node modules are distributed through the Node Package Manager
(npm), which is a package manager bundled with Node.js. npm allows developers to discover, install, and manage dependencies for their Node.js projects effortlessly. It hosts a vast registry of open-source modules that can be freely used and shared.
OS Node Module
The os module
in Node.js provides a set of utility functions to interact with the operating system. It allows you to access various information and perform operations related to the underlying operating system.
Some Common OS
Node Module features are mentioned below -
- os.platform(): Returns the platform name.
- os.arch(): Returns the CPU architecture.
- os.totalmem(): It is used to return the total amount of system memory in bytes.
- os.freemem(): It is used to the amount of free system memory in bytes.
- os.cpus(): It is used to return an array of objects containing information about each logical CPU core.
- os.userInfo(): Returns information about the current user, such as username and home directory.
- os.networkInterfaces(): Returns an object with network interface names as keys and an array of associated addresses as values.
- os.hostname(): It is used to return the hostname of the operating system.
- os.endianness(): Returns the endianness of the CPU architecture ('BE' for big endian, 'LE' for little endian).
Path Node Module
The path module in Node.js provides utilities for working with file paths. It offers functions to manipulate and interact with file paths in a platform-independent manner.
The features of the Path Node Module
are mentioned below -
- Path Normalization: The path.normalize() function is used to normalize a given path by resolving . and .. segments and removing redundant slashes.
const path = require('path'); const normalizedPath = path.normalize('/path/to/dir/..//file.txt'); console.log(normalizedPath); // Output: '/path/to/file.txt'
- Joining Path Segments: The path.join() function is used to join multiple path segments into a single path string. It takes individual path segments as arguments and returns the concatenated path.
const path = require('path'); const joinedPath = path.join('/path', 'to', 'dir', 'file.txt'); console.log(joinedPath); // Output: '/path/to/dir/file.txt'
- Resolving Absolute Path: The path.resolve() function is used to resolve an absolute path from a given sequence of paths or path segments. It returns the absolute path based on the current working directory.
const path = require('path'); const absolutePath = path.resolve('path/to', 'file.txt'); console.log(absolutePath); // Output: '/current/working/directory/path/to/file.txt'
- Extracting Path Components: The path.dirname() and path.basename() functions are used to extract the directory name and the base name of a file path, respectively.
const path = require('path'); const directoryName = path.dirname('/path/to/file.txt'); console.log(directoryName); // Output: '/path/to' const baseName = path.basename('/path/to/file.txt'); console.log(baseName); // Output: 'file.txt'
- File Extension: The path.extname() function returns the extension of a file path.
const path = require('path'); const extension = path.extname('/path/to/file.txt'); console.log(extension); // Output: '.txt'
- Path Segments: The path.sep property provides the platform-specific path segment separator. It can be used to split a path string into an array of segments.
const path = require('path'); const segments = '/path/to/file.txt'.split(path.sep); console.log(segments); // Output: ['', 'path', 'to', 'file.txt']

File System Node Module
The File System module
, commonly referred to as fs, is a built-in module in Node.js that provides an API for interacting with the file system. It allows you to perform various file-related operations, such as reading from and writing to files, creating and deleting files and directories, modifying file permissions, and more.
The fs module
provides both synchronous and asynchronous versions of its functions, allowing you to choose the appropriate approach based on your application's requirements.
Some Features of the File System Node Modules
are mentioned below -
- File Reading and Writing: The
fs.readFile()
andfs.writeFile()
functions are used to read content from a file and write content to a file, respectively.
const fs = require('fs'); fs.readFile('path/to/file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
fs.writeFile('path/to/file.txt', 'Hello, World!', 'utf8', (err) => { if (err) throw err; console.log('File written successfully.'); });
- File and Directory Manipulation: The fs module provides functions for creating, renaming, copying, and deleting files and directories.
const fs = require('fs'); fs.mkdir('path/to/new-directory', (err) => { if (err) throw err; console.log('Directory created successfully.'); });
fs.rename('path/to/old-file.txt', 'path/to/new-file.txt', (err) => {
if (err) throw err;
console.log('File renamed successfully.');
});
fs.unlink('path/to/file.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully.');
});
- File Information: The fs.stat() function allows you to retrieve information about a file, such as its size, permissions, and modification timestamp.
const fs = require('fs'); fs.stat('path/to/file.txt', (err, stats) => { if (err) throw err; console.log('File size:', stats.size); console.log('File permissions:', stats.mode); console.log('Last modified:', stats.mtime); });
- File Permissions: The fs.chmod() function is used to change the permissions of a file. It allows you to set read, write, and execute permissions for the owner, group, and others.
const fs = require('fs'); fs.chmod('path/to/file.txt', 0o644, (err) => { if (err) throw err; console.log('File permissions changed successfully.'); });
- Directory Listing: The fs.readdir() function allows you to retrieve a list of files and directories within a directory.
const fs = require('fs'); fs.readdir('path/to/directory', (err, files) => { if (err) throw err; console.log('Files in directory:', files); });
HTTP Node Module
The http module is a built-in module in Node.js that provides functionality for creating HTTP servers and making HTTP requests. It allows you to build web servers, handle incoming HTTP requests, and make HTTP requests to external servers. The http module provides both server and client functionalities.
The features of the HTTP Node Module Client and Server are mentioned below -
HTTP Server:
- Creating a Server: You can create an HTTP server using the http.createServer() method. This method takes a callback function that is executed whenever a request is received by the server.
const http = require('http');
const server = http.createServer((req, res) => { // Request handling logic });
- Handling Requests: In the server callback function, you can handle incoming requests and send responses. You can access the request headers, URL, and other information from the req object, and send the response using the res object.
const http = require('http');
const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!'); });
- Starting the Server: After creating the server, you need to start it and listen for incoming requests. You can use the server.listen() method to specify the port and optional host to listen on.
const http = require('http');
const server = http.createServer((req, res) => {
// code
});
server.listen(3000, 'localhost', () => {
console.log('Server started on port 3000');
});
HTTP Client:
- Making HTTP Requests: The http module also allows you to make HTTP requests to external servers. You can use the http.request() method to create a request object and send it to the server.
const http = require('http');
const options = {
hostname: 'api.example.com',
path: '/users',
method: 'GET'
};
const req = http.request(options, (res) => {
// Response handling logic
});
req.end();
- Handling Responses: In the request callback function, you can handle the server's response. You can read the response data, status code, headers, etc. from the res object.
const http = require('http');
const options = {
hostname: 'api.example.com',
path: '/users',
method: 'GET'
};
const req = http.request(options, (res) => {
let responseData = '';
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
console.log(responseData);
});
});
req.end();
Library
WEB DEVELOPMENT
Basic
Frontend
Backend
Node JS
Node Modules
Restful Routing
Static Files
REST API
Introduction to Node JS
GET vs POST
Database
Interview Questions
FAANG QUESTIONS
On this page
OS Node Module
Path Node Module
File System Node Module
HTTP Node Module