Unlocking the Power of Node.js: A Guide to Built-in Modules

Node.js has changed the game for server-side development with its fast and efficient event-driven model. One of the best things about Node.js is its built-in modules, which come packed with useful features right out of the box. These modules save a lot of time and effort by handling common tasks, so you can focus on writing your application.

Whether you’re working with file systems, streams, or creating HTTP servers, Node.js has a module. Knowing these built-in modules is essential for any Node.js developer because they are the foundation of most applications. In this blog, I’ll review some of the must-know built-in modules that can make your Node.js projects more efficient and powerful.

Prerequisite

Basic Understanding of Node.js: Familiarity with Node.js fundamentals such as event-driven architecture, non-blocking I/O operations, and modules (require/import).

Node.js Installation: Ensure Node.js is installed on your system to execute JavaScript code outside the browser environment.

Knowledge of JavaScript: Proficiency in JavaScript programming language, including ES6+ features like arrow functions, destructuring, and classes.

Node Built-in Modules

1. HTTP Module

The HTTP module in Node.js provides functionality to create HTTP servers and make HTTP requests. It allows Node.js applications to act as web servers, enabling them to handle incoming HTTP requests and respond with appropriate HTTP responses. This module is essential for building web applications, APIs, and server-side functionality in Node.js.

//Create a server instance
const http = require('http');

//Create a server instance
const server = http.createServer((req, res) => {
    // Request handling logic here
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!\n');
});

//Listen on a specific port
const port = 3000;
server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

require(‘http’): This statement imports the HTTP module, making its functionality accessible in your Node.js script.

http.createServer(): This method creates an HTTP server instance. It takes a callback function (req, res) that gets invoked whenever a request is made to the server.

  • req: Represents the HTTP request object containing details such as URL, HTTP method, headers, etc.
  • res: Represents the HTTP response object used to send data back to the client.

res.writeHead(statusCode, headers): This method sets the HTTP response header.In the example, res.writeHead(200, { ‘Content-Type’: ‘text/plain’ }) sets the status code to 200 (indicating a successful response) and specifies that the content type of the response is plain text (‘text/plain’).

res.end(data): This method sends the response data (‘Hello, World!\n’ in this case) to the client and ends the response.

2. Events Module

EventEmitter is one of the core classes in Node that allows us to raise (emit) and handle events. Several built-in classes in Node derive from EventEmitter. This class implements the observer pattern, where an object (the emitter) maintains a list of functions (listeners) to be called when a specific event occurs. This pattern is crucial for building scalable and decoupled applications in Node.js, enabling different parts of the application to communicate asynchronously.

//Import the Events module
const EventEmitter = require('events');

//Create an EventEmitter instance
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

//Listen for events
myEmitter.on('event', (arg1, arg2) => {
    console.log('Event occurred with arguments:', arg1, arg2);
});

//Emit events
myEmitter.emit('event', 'arg1value', 'arg2value');

require(‘events’): This statement imports the Events module, making the EventEmitter class accessible in your Node.js script.

EventEmitter Class: The EventEmitter class is extended to create custom event emitters (MyEmitter in the example). Instances of EventEmitter can emit events and register listeners to handle those events.

myEmitter.on(eventName, listener): This method registers a listener function listener for the specified eventName. When the event eventName is emitted, the listener function is executed with any supplied arguments.

myEmitter.emit(eventName, [args]): This method emits an event eventName with optional arguments [args]. When emit is called, all registered listeners for eventName are called synchronously in the order they were registered.

3. OS Module

The OS module in Node.js provides operating system-related utility methods and properties. It allows you to access information about the operating system on which the Node.js process is running, such as CPU architecture, memory, network interfaces, and more. This module is particularly useful for tasks that require system-level information and operations within Node.js applications.

const os = require('os');

// Get the operating system platform
console.log('Platform:', os.platform());

// Get the operating system release version
console.log('OS Release:', os.release());

// Get the CPU architecture
console.log('CPU Architecture:', os.arch());

// Get information about each CPU/core
console.log('CPUs:', os.cpus());

// Get total system memory
console.log('Total Memory:', os.totalmem());

require(‘os’): This statement imports the OS module, providing access to its functionality within your Node.js script.

os.platform(): Returns a string identifying the operating system platform (e.g., ‘darwin’, ‘linux’, ‘win32’).

os.release(): Returns a string identifying the operating system release version.

os.arch(): Returns a string identifying the CPU architecture (e.g., ‘x64’, ‘arm’).

os.cpus(): Returns an array of objects containing information about each CPU/core, including speed and model.

os.totalmem(): Returns the total amount of system memory in bytes.

Related read: Best Node.js Frameworks to Use in 2024

Build Powerful Node.js Apps. Hire Our Developers Now!

4. Path Module

The Path module in Node.js provides utilities for working with file and directory paths. It offers methods to handle and transform file paths in a way that is cross-platform compatible (i.e., works seamlessly across different operating systems like Windows, macOS, and Linux). This module simplifies tasks related to file system manipulation and path resolution within Node.js applications.

const path = require('path');

// Joining paths
const fullPath = path.join('/folder', 'subfolder', 'file.txt');
console.log('Full Path:', fullPath);

// Normalizing a path
const normalizedPath = path.normalize('/folder//subfolder/../file.txt');
console.log('Normalized Path:', normalizedPath);

// Resolving an absolute path
const absolutePath = path.resolve('folder', 'subfolder', 'file.txt');
console.log('Absolute Path:', absolutePath);

// Parsing a path
const parsedPath = path.parse('/folder/subfolder/file.txt');
console.log('Parsed Path:', parsedPath);

5. File System Module

The File System (fs) module in Node.js provides APIs for interacting with the file system. It allows you to perform file-related operations such as reading from and writing to files, creating directories, updating file permissions, and more. This module is essential for implementing file-based data storage, manipulation, and management within Node.js applications.

const fs = require('fs');

// Reading from a file
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log('File Content:', data);
});

// Writing to a file
const content = 'This is a test file content.';
fs.writeFile('test.txt', content, (err) => {
if (err) throw err;
console.log('File has been saved!');
});

// Checking if a file or directory exists
fs.access('file.txt', fs.constants.F_OK, (err) => {
if (err) {
console.error('File does not exist');
return;
}
console.log('File exists');
});

// Creating a directory
fs.mkdir('newDir', { recursive: true }, (err) => {
if (err) throw err;
console.log('Directory created successfully');
});

require(‘fs’): This statement imports the File System module, allowing access to its methods within your Node.js script.

fs.readFile(path, options, callback): Reads data from a file asynchronously. The path specifies the file to be read, options specify the encoding (optional), and the callback function is called with the file data or an error if it occurs.

fs.writeFile(file, data, callback): Writes data to a file asynchronously. file is the file name or path, data is the content to be written, and callback is called once the operation completes (with an optional error).

fs.access(path, mode, callback): Checks the accessibility of a file or directory. path is the file or directory to check, mode specifies the accessibility mode (e.g., fs.constants.F_OK for existence check), and callback is called with an error if the path is not accessible.

fs.mkdir(path, options, callback): Creates a new directory asynchronously. Path specifies the directory path to be created, options can include properties like recursive (to create nested directories if necessary), and callback is called once the directory is created (or with an error if it occurs).

coma

Conclusion

Node.js provides essential built-in modules that streamline core functionalities like handling file systems, managing paths, networking, and accessing operating system details. Among these modules, EventEmitter stands out by facilitating event-driven programming, allowing applications to handle asynchronous events efficiently. The File System module simplifies file operations such as reading, writing, and managing directories, crucial for data manipulation tasks.

Similarly, the Path module ensures seamless cross-platform compatibility when working with file and directory paths, enhancing application portability. Together, these modules empower developers to build robust and scalable Node.js applications,utilizing Node.js’s strengths in handling diverse application requirements effectively.

Nadeem K

Associate Software Engineer

Nadeem is a front-end developer with 1.5+ years of experience. He has experience in web technologies like React.js, Redux, and UI frameworks. His expertise in building interactive and responsive web applications, creating reusable components, and writing efficient, optimized, and DRY code. He enjoys learning about new technologies.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?