Node.js - Helpful Built-in Modules

From reading files to creating web servers, built-in modules are the silent workhorses that power many Node.js applications. In this article, we'll explore some of the useful built-in modules that you might find useful in your projects.

These built-in modules are core modules that come pre-installed with Node.js. They provide a wide range of functionality, from file system operations to creating web servers. Let's look at four handy modules:

  • fs (File System)
  • path
  • http
  • os (Operating System)

The fs Module: File System Operations

The fs module allows you to work with your computer's file system. It provides methods for reading, writing, and manipulating files and directories.

Imagine you're building a log analysis tool for a busy e-commerce website. You need to read large log files, process the data, and write reports. The fs module would be your go-to tool for these file operations.

Reading a File

Here's a simple example of how to read a file:

const fs = require('fs');

fs.readFile('server-logs.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading log file:', err);
    return;
  }
  console.log('Log contents:', data);
});

This code reads the contents of 'server-logs.txt' and logs it to the console. The utf8 parameter specifies the file encoding.

Writing to a File

Writing to a file is just as straightforward:

const fs = require('fs');

const logSummary = 'Total visits: 15000, Unique users: 3500';

fs.writeFile('log-summary.txt', logSummary, (err) => {
  if (err) {
    console.error('Error writing summary file:', err);
    return;
  }
  console.log('Log summary written successfully');
});

This script creates (or overwrites) a file named 'log-summary.txt' with a summary of the log data.

The path Module: Navigating the File System

The path module provides utilities for working with file and directory paths. This is especially useful when your application needs to work across different operating systems, which may use different path formats.

Consider developing a cross-platform desktop application that needs to store user data in specific locations on Windows, macOS, and Linux. The path module would help you construct the correct file paths for each operating system.

Key Path Operations

const path = require('path');

// Joining path segments
console.log(path.join('user', 'documents', 'app-data', 'config.json'));
// Output: user/documents/app-data/config.json

// Getting the base filename
console.log(path.basename('/user/documents/app-data/config.json'));
// Output: config.json

// Getting the directory name
console.log(path.dirname('/user/documents/app-data/config.json'));
// Output: /user/documents/app-data

// Getting the file extension
console.log(path.extname('config.json'));
// Output: .json

These utilities help you manipulate and extract information from file paths in a consistent way across different operating systems.

The http Module: Building Your Own Web Server

One of the things that is most popular to do with Node.js is building servers. Although it's not the focus of this course it's worth sharing that the http module allows you to create HTTP servers and make HTTP requests.

Imagine you're creating a simple API for a mobile app that needs to serve JSON data. The http module would be the foundation for building this API server.

Creating a Basic Web Server

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message: 'Hello, Mobile App!' }));
});

server.listen(3000, () => {
  console.log('API server running at http://localhost:3000/');
});

This code creates a server that responds with a JSON message to all requests. The server listens on port 3000.

The os Module: Understanding Your System Environment

The os module provides information about the computer's operating system. This can be useful for tasks that adapt to the system environment.

Let's say you're building a system monitoring dashboard. The os module would allow you to gather and display key system information.

Retrieving System Information

const os = require('os');

console.log('OS Platform:', os.platform());
console.log('OS Type:', os.type());
console.log('Total Memory:', (os.totalmem() / (1024 * 1024 * 1024)).toFixed(2), 'GB');
console.log('Free Memory:', (os.freemem() / (1024 * 1024 * 1024)).toFixed(2), 'GB');
console.log('CPU Cores:', os.cpus().length);

This script provides basic information about the operating system, including the platform, type, memory, and number of CPU cores.

Further Learning

These examples scratch the surface of what Node.js built-in modules can do. To learn more about these and other built-in modules, you can refer to the official Node.js documentation:

Node.js v20.x Documentation

This documentation provides comprehensive information on all built-in modules, including detailed explanations of their methods and properties.


In our next article, we'll expand on our CLI tool from a previous chapter, putting these modules to practical use. We'll see how these built-in modules can significantly enhance the functionality of our applications.

Remember, the key to mastering these modules is practice. Try incorporating them into your projects, experiment with different methods, and don't hesitate to refer to the documentation as you explore their capabilities.

BeginnerNodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.