Paramclasses Academy - Blog

Tutorials Details

←
Post 9 of 40
→

Node.js File System Module: Read, Write, Update and Delete Files

Node.js File System Module: Read, Write, Update and Delete Files

October 29, 2026

✦ Node.js File System Module: Read, Write, Update and Delete Files

In Node.js development, working with files is a common requirement. You may need to read student records, save application data, create reports, update text files, or delete temporary files. Node.js provides a built-in module called File System (fs) to perform these operations.

The File System module allows developers to interact with files and directories on their computers or servers. You can use it to build practical applications such as billing software, student management systems, log generators, and file-processing tools.

In this tutorial by Param Classes, you will learn how to use the Node.js fs module with practical examples of reading, writing, appending, updating, and deleting files.

✦ What Is the File System Module in Node.js?

The fs module is a built-in Node.js module that provides functions for working with the file system. You do not need to install it separately using npm.

You can import it using CommonJS:

const fs = require('fs');

Or use ES Modules:

import fs from 'node:fs';

Both approaches provide access to file-system functionality. This tutorial uses CommonJS for the main examples.

❖ Why Is the fs Module Important?

The File System module helps developers:

  • Read data from text and JSON files.

  • Create new files.

  • Write and append content.

  • Update existing file data.

  • Delete files.

  • Create and manage directories.

  • Store application logs and reports.

For example, a billing application might save invoice records to files, while a student management application might read student information from a JSON file.

✦ Step 1: Create Your First Node.js Project

First, ensure Node.js is installed. Open your terminal and check:

node -v
npm -v

Create a project directory:

mkdir node-fs-demo
cd node-fs-demo
npm init -y

Create a file named app.js.

Your project structure will look like this:

node-fs-demo/
├── app.js
└── package.json

Because fs is built into Node.js, no additional package installation is required.

✦ Step 2: Write Data to a File

The fs.writeFile() method creates a file if it does not exist or replaces its contents if it already exists.

Example:

const fs = require('fs');

fs.writeFile('student.txt', 'Welcome to Param Classes!', (err) => {
    if (err) {
        console.error('Error writing file:', err);
        return;
    }

    console.log('File created successfully!');
});

Save the code in app.js and run:

node app.js

Expected output:

File created successfully!

A file named student.txt will be created in your project directory.

Its contents will be:

Welcome to Param Classes!

Important: writeFile() replaces the existing contents of a file. If you want to add content without removing the existing text, use appendFile().

✦ Step 3: Read Data from a File

The fs.readFile() method reads the contents of a file.

Example:

const fs = require('fs');

fs.readFile('student.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }

    console.log('File content:', data);
});

Output:

File content: Welcome to Param Classes!

Here, 'utf8' tells Node.js to return the file content as a text string.

Without an encoding, the result is a Buffer object containing the file data.

❖ What Happens If the File Does Not Exist?

If the file cannot be found, the callback receives an error.

This is why checking err is important. It prevents your application from treating a failed read as successful.

✦ Step 4: Append New Data to a File

Sometimes you need to add new content while preserving existing data. For this, use fs.appendFile().

Example:

const fs = require('fs');

fs.appendFile('student.txt', '\nNew student registered.', (err) => {
    if (err) {
        console.error('Error appending data:', err);
        return;
    }

    console.log('New data added successfully!');
});

After running the code, student.txt will contain:

Welcome to Param Classes!
New student registered.

This method is useful for simple logs, activity records, and text-based reports.

However, for complex application data involving multiple users or simultaneous updates, a proper database is usually a better choice.

✦ Step 5: Update File Content

There are different ways to update a file, depending on what you want to change.

❖ Method 1: Replace the Entire File

Use writeFile() when you want to replace the existing contents.

const fs = require('fs');

fs.writeFile('student.txt', 'Updated student information.', (err) => {
    if (err) {
        console.error(err);
        return;
    }

    console.log('File updated successfully!');
});

The previous contents are replaced with the new text.

❖ Method 2: Replace Specific Text

To update a particular piece of text, read the file, replace the required value, and write the modified content back.

const fs = require('fs');

fs.readFile('student.txt', 'utf8', (err, data) => {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }

    const updatedData = data.replace(
        'Updated student information',
        'Student information verified'
    );

    fs.writeFile('student.txt', updatedData, (writeErr) => {
        if (writeErr) {
            console.error('Error updating file:', writeErr);
            return;
        }

        console.log('Student information updated!');
    });
});

This example replaces the first matching occurrence of the specified text.

Note: Reading and then writing a file is not an atomic update. If multiple processes may modify the same file, data can be overwritten. For important records, consider a database or an appropriate file-locking and concurrency strategy.

✦ Step 6: Delete a File

Node.js provides fs.unlink() to delete a file.

Example:

const fs = require('fs');

fs.unlink('student.txt', (err) => {
    if (err) {
        console.error('Error deleting file:', err);
        return;
    }

    console.log('File deleted successfully!');
});

Output:

File deleted successfully!

The file is removed if the operation succeeds.

Important: Deleting a file is potentially irreversible. Before using deletion code in a real application, verify the file path and ensure the file is safe to remove.

✦ Step 7: Use Synchronous File Operations

The fs module also provides synchronous methods. These methods wait for the operation to complete before the next statement executes.

For example:

const fs = require('fs');

try {
    fs.writeFileSync('message.txt', 'Hello from Node.js');

    const data = fs.readFileSync('message.txt', 'utf8');

    console.log(data);
} catch (err) {
    console.error('File operation failed:', err.message);
}

Output:

Hello from Node.js

Here, writeFileSync() writes the content, and readFileSync() reads it.

Synchronous methods are straightforward for small scripts and simple tasks. However, they block the JavaScript execution thread while the file operation is in progress. For web servers handling multiple requests, asynchronous methods are generally preferable.

✦ Step 8: Use Promises with async/await

Node.js also provides a promise-based File System API. It is available through fs/promises.

This approach is useful when you want to write asynchronous code in a sequential style.

Example:

const fs = require('node:fs/promises');

async function manageFile() {
    try {
        await fs.writeFile(
            'student.txt',
            'Student Name: Rahul\nCourse: Node.js'
        );

        const data = await fs.readFile('student.txt', 'utf8');

        console.log(data);
    } catch (err) {
        console.error('File operation failed:', err.message);
    }
}

manageFile();

Output:

Student Name: Rahul
Course: Node.js

The await keyword waits for each promise to settle before continuing inside the asynchronous function. It does not block the entire Node.js event loop in the same way as synchronous file operations.

This style is commonly used in modern Node.js applications.

✦ Step 9: Create a Directory

You can create a directory using fs.mkdir().

const fs = require('fs');

fs.mkdir('uploads', { recursive: true }, (err) => {
    if (err) {
        console.error('Error creating directory:', err);
        return;
    }

    console.log('Uploads directory created!');
});

The recursive: true option allows Node.js to create missing parent directories when necessary. It also avoids an error if the target directory already exists.

This can be useful when organizing uploaded documents, generated reports, and application files.

✦ Important File System Methods

Method Purpose
fs.readFile() Read file content asynchronously
fs.writeFile() Create or replace file content
fs.appendFile() Add content to a file
fs.unlink() Delete a file
fs.mkdir() Create a directory
fs.readdir() Read directory contents
fs.rename() Rename or move a file
fs.stat() Retrieve file or directory information
fs.readFileSync() Read a file synchronously
fs.promises.readFile() Read a file using promises

Choose the method that matches your task and use error handling for operations that can fail.

✦ Best Practices for Using the fs Module

Follow these guidelines when working with files in real projects.

  1. Handle errors: Always check errors returned by callbacks or rejected promises.

  2. Prefer asynchronous operations in servers: Avoid blocking the event loop unnecessarily.

  3. Validate file paths: Do not blindly trust paths supplied by users.

  4. Protect sensitive files: Restrict access to private documents, credentials, and application configuration.

  5. Use suitable storage: A database is usually more appropriate for structured records that need concurrent updates and queries.

  6. Avoid accidental overwrites: Remember that writeFile() replaces existing content.

  7. Test file operations: Check missing files, permissions, invalid paths, and unexpected input.

✦ Frequently Asked Questions (FAQs)

❖ 1. What is the fs module in Node.js?

The fs module is a built-in Node.js module used to read, write, append, update, and delete files and manage directories.

❖ 2. Do I need to install the fs module?

No. The File System module is included with Node.js.

❖ 3. What is the difference between writeFile and appendFile?

writeFile() replaces existing file content, while appendFile() adds content to the end of a file.

❖ 4. What is the difference between synchronous and asynchronous file operations?

Synchronous operations block the JavaScript execution thread until the operation completes. Asynchronous operations allow other JavaScript work to continue while waiting for the file operation.

❖ 5. How can I delete a file in Node.js?

Use fs.unlink() or its promise-based equivalent to remove a file.

❖ 6. Can Node.js read JSON files?

Yes. You can read a JSON file as text with fs.readFile() and parse it using JSON.parse(), handling parsing errors appropriately.

✦ Conclusion

The Node.js File System module is a useful tool for working with files and directories. By learning how to read, write, append, update, and delete files, you can build practical utilities and understand how backend applications handle file-based data.

The next step is to combine these techniques with Express.js, databases, and proper input validation to develop more complete applications.

At Param Classes, learners can explore practical Node.js programming concepts through step-by-step examples.

Visit Param Classes for programming tutorials and ParamWebInfo for website development and digital solutions.

 

←
Post 9 of 40
→