Node.js Internal Modules: fs, http, path & events

Unlock the power of Node.js by mastering its built-in tools for file systems, networking, and more.

Welcome! Node.js has powerful built-in tools called 'modules'. Let's learn how to use them.

/* Starting our Node.js journey... */

The `fs` Module: Your File System Gateway

The File System (`fs`) module is your tool for interacting with the computer's file system. You can use it to read, write, update, and delete files and directories. It's fundamental for any application that needs to persist data or manage assets.

The `http` Module: Building Web Servers

The HTTP (`http`) module is the backbone for networking in Node.js. It allows you to create web servers that listen for requests and send back responses, making it essential for building APIs and websites.

The `path` Module: Navigating File Paths

The Path (`path`) module provides utilities for working with file and directory paths. It helps normalize paths to work consistently across different operating systems (like Windows, macOS, and Linux), preventing common bugs.

The `events` Module: Asynchronous Communication

The Events (`events`) module is key to Node.js's asynchronous, event-driven architecture. It allows you to create, emit, and listen for custom events, enabling a robust "publish-subscribe" pattern for decoupled code.

Practice Zone


Interactive Test 1: Match the Module

Match the Node.js module to its primary function.

Arrastra en el orden correspondiente.


Arrastra las opciones:

http
path
fs

Completa el código:

Reading files______
Creating a server______
Joining paths______
Unlock with Premium

Interactive Test 2: Complete the Code

Rellena los huecos en cada casilla.

// We need to create a server and read a file
const http = require('');
const fs = require('');
Unlock with Premium

Practice Example: Code Editor

Using the `fs` module, write code to read a file named `message.txt` synchronously using UTF-8 encoding.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

const fs = require('fs'); try { const data = fs.readFileSync('message.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); }
Unlock with Premium

Knowledge Check

Which Node.js internal module is essential for creating a web server?


Unlock with Premium

Node.js Modules in Action

Node's internal modules are the building blocks for almost any server-side application. Here’s how they work together in common scenarios.


1. Serving a Static HTML File

A fundamental task for a web server is to serve files. By combining the `http` module to create the server and the `fs` module to read the file from disk, you can easily serve a web page.

const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
  fs.readFile('index.html', (err, data) => {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

2. Building a Command-Line Tool (CLI)

Node.js excels at creating scripts. Using `fs` to read/write files and `path` to construct reliable file paths, you can build a tool that, for example, renames all files in a directory according to a pattern.

const fs = require('fs');
const path = require('path');

const targetDir = './my-files';

fs.readdir(targetDir, (err, files) => {
  files.forEach(file => {
    const oldPath = path.join(targetDir, file);
    const newPath = path.join(targetDir, `prefix-${file}`);
    fs.rename(oldPath, newPath, () => {});
  });
});

3. Creating a Custom Logger with Events

The `events` module is perfect for decoupling parts of your application. You can create a logger that listens for 'error' or 'success' events from other parts of your code and writes them to a file using `fs`.

const EventEmitter = require('events');
const fs = require('fs');

class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

myEmitter.on('log', (msg) => {
  fs.appendFile('app.log', `${new Date()}: ${msg}\
`, () => {});
});

// In another part of the app:
myEmitter.emit('log', 'User logged in successfully.');

Practical Takeaway: Mastering the core modules allows you to build powerful, efficient applications from the ground up and gives you a deep understanding of how the Node.js ecosystem works.

Node.js Core Glossary

Module
A reusable block of code encapsulated in a file. Node.js has core (internal) modules, and you can install third-party modules from npm or create your own.
require()
The CommonJS function used in Node.js to import modules. It reads a JavaScript file, executes it, and returns the `exports` object.
Asynchronous I/O
Input/Output operations (like reading a file or making a network request) that are non-blocking. Node.js performs the operation in the background and executes a callback function once it's complete, allowing the main program to continue running.
Event-Driven Architecture
A programming paradigm where the flow of the program is determined by events, such as a user clicking a button or a server receiving a new connection. The `events` module is the foundation for this in Node.js.
Process
A global object in Node.js that provides information about, and control over, the current Node.js process. It's used for accessing environment variables (`process.env`) or exiting the script (`process.exit()`).