2 Hours

4. File System (fs Module)

File I/O

Reading and Writing Files

Node.js Memory Efficiency: Streams vs Buffers Buffering loads the entire file into RAM at once; Streaming chunks data with fixed memory usage fs.readFile() — Full Buffer Allocation (Memory Bottleneck) 1 GB File → Allocates 1 GB Heap RAM ✗ Can crash server with Out-Of-Memory (OOM) fs.createReadStream().pipe() — Stream Chunking (Constant Memory) Chunk 1 (64KB) Chunk 2 (64KB) Chunk 3 (64KB) ✓ Handles 100GB files with only ~20MB RAM usage!

The fs (File System) module allows Node.js to read, write, delete, and manage files on your computer's hard drive. This is essential for logging, configuration files, and handling user uploads.

Reading a File Asynchronously

fs.readFile() reads a file without blocking the event loop. Reading from disk is slow (takes milliseconds), so if it blocked, your server would freeze for every file read. The promise version lets you use async/await for clean code.

JavaScript
const fs = require('fs/promises');

async function readFile() {
    const data = await fs.readFile('example.txt', 'utf8');
    console.log(data);
}

readFile();

Try it: Create an example.txt file with some text. Run this code to read it.

Writing a File

fs.writeFile() creates a new file or overwrites an existing one. If the file doesn't exist, it creates it. If it does exist, it replaces all the content. This is useful for saving configuration or generating reports.

JavaScript
const fs = require('fs/promises');

async function writeFile() {
    await fs.writeFile('log.txt', 'Server started at ' + new Date());
    console.log('File written!');
}

writeFile();

Appending to a File

fs.appendFile() adds content to the END of a file without deleting what's already there. This is perfect for log files where you want to keep history. Each new log entry is added to the bottom without losing previous entries.

JavaScript
const fs = require('fs/promises');

async function appendLog() {
    await fs.appendFile('access.log', 'New request received
');
    console.log('Appended to log');
}

appendLog();

Try it: Run this multiple times. Each run adds a new line without deleting previous lines.

Deleting a File

fs.unlink() deletes a file. unlink is the Unix system call name for deleting files. Always wrap this in try/catch because the file might not exist, and trying to delete a missing file throws an error.

JavaScript
const fs = require('fs/promises');

async function deleteFile() {
    try {
        await fs.unlink('temp.txt');
        console.log('File deleted');
    } catch (err) {
        console.log('File did not exist');
    }
}

deleteFile();

Working with Directories

fs.mkdir() creates folders. The { recursive: true } option creates parent folders automatically if they don't exist. fs.readdir() lists all files and folders inside a directory, returning an array of names.

JavaScript
const fs = require('fs/promises');

async function manageFolders() {
    await fs.mkdir('uploads/user123', { recursive: true });
    const files = await fs.readdir('uploads');
    console.log('Folders:', files);
}

manageFolders();

Checking if a File Exists

fs.access() checks if you can read or write a file. It throws an error if the file doesn't exist or if you don't have permission. Use try/catch to handle the does not exist case gracefully.

JavaScript
const fs = require('fs/promises');

async function fileExists() {
    try {
        await fs.access('config.json');
        console.log('File exists!');
    } catch {
        console.log('File does NOT exist');
    }
}

fileExists();

Knowledge Check

Ready to test your understanding of 4. File System (fs Module)?

Back