Lesson 13 of 50 – Reading and Writing Files
26% Completed
26%

Reading and Writing Files in Node.js

Node.js provides file system methods that allow us to read data from files and write new data into files. These operations are useful for storing information, reading configuration files, generating reports, and managing application data.

In simple words: Reading means getting data from a file, while writing means saving data into a file.

1. Importing the File System Module

The built-in fs module provides methods for reading and writing files. We do not need to install an extra package.

CommonJS Example
const fs = require('node:fs');

console.log("File System Module Ready");

Output:

File System Module Ready

This example uses CommonJS syntax. If your project uses ES Modules, you can write import fs from 'node:fs'; instead.

2. Writing Data Using writeFileSync()

The writeFileSync() method writes data to a file. It creates the file if it does not exist and replaces existing contents by default.

Example: Write a File

Create a file named write.js:

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

fs.writeFileSync('message.txt', 'Hello Students');

console.log("Data written successfully");

Output:

Data written successfully

A file named message.txt will contain:

Hello Students

3. Reading Data Using readFileSync()

The readFileSync() method reads a file synchronously. Passing 'utf8' tells Node.js to return the file contents as a string.

Example: Read a File
const fs = require('node:fs');

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

console.log(data);

Output:

Hello Students
The file must exist at the specified path. Otherwise, the synchronous read operation throws an error.

4. Writing Multiple Lines

We can use the newline character \n to write multiple lines into a file.

Example: Multiple Lines
const fs = require('node:fs');

const content = "Name: Amit\nCourse: Node.js\nCity: Gaya";

fs.writeFileSync('student.txt', content);

console.log("Student information saved");

Contents of student.txt:

Name: Amit
Course: Node.js
City: Gaya

5. Appending Data Using appendFileSync()

The appendFileSync() method adds new data to the end of a file instead of replacing its existing contents.

Example: Append Data

Suppose message.txt contains:

Hello Students

Now run:

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

fs.appendFileSync('message.txt', '\nWelcome to Node.js');

console.log("New data added");

Updated file contents:

Hello Students
Welcome to Node.js

6. Writing Files Asynchronously

The asynchronous writeFile() method allows Node.js to continue doing other work while the file operation is pending. Its callback receives an error if the operation fails.

Example: writeFile()
const fs = require('node:fs');

fs.writeFile('async.txt', 'Hello from asynchronous Node.js', function(err) {
    if (err) {
        console.error("Error writing file:", err.message);
        return;
    }

    console.log("File written successfully");
});

console.log("Write operation started");

The message Write operation started may appear before the success message because the file operation is asynchronous.

7. Reading Files Asynchronously

The asynchronous readFile() method reads a file and passes its contents to a callback when the operation finishes.

Example: readFile()
const fs = require('node:fs');

fs.readFile('async.txt', 'utf8', function(err, data) {
    if (err) {
        console.error("Error reading file:", err.message);
        return;
    }

    console.log("File contents:", data);
});

console.log("Reading started");

Possible output order:

Reading started
File contents: Hello from asynchronous Node.js

The file must exist before it can be read successfully. Run the previous writing example first.

8. Using Promises with File Operations

Node.js provides node:fs/promises, which offers promise-based file operations. These work well with async and await.

Example: Promise-Based File Reading
const fs = require('node:fs/promises');

async function readStudentFile() {
    try {
        const data = await fs.readFile('student.txt', 'utf8');
        console.log(data);
    } catch (err) {
        console.error("Unable to read file:", err.message);
    }
}

readStudentFile();

The await keyword waits for the file-reading promise to settle inside the asynchronous function. The try...catch block handles errors.

9. Choosing the Right Method

Method Purpose Behavior
writeFileSync() Write or replace file contents Synchronous
readFileSync() Read file contents Synchronous
appendFileSync() Add data to a file Synchronous
writeFile() Write file contents Asynchronous callback
readFile() Read file contents Asynchronous callback
fs/promises Promise-based file operations Works with async/await

10. Practical Assignment

Practice Task
Create a Node.js program to manage a simple student file.
  1. Create a file named students.txt with the text Student 1: Amit.
  2. Read and display the file contents.
  3. Append Student 2: Rahul on a new line.
  4. Read the file again and display the updated contents.
  5. Use an asynchronous method to write File operation completed to another file.
  6. Handle errors using callbacks or try...catch.

Hint:

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

fs.writeFileSync('students.txt', 'Student 1: Amit');

fs.appendFileSync('students.txt', '\nStudent 2: Rahul');

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

console.log(data);

Expected output:

Student 1: Amit
Student 2: Rahul

🧠 Quiz – Reading and Writing Files

Select the correct answer for each question.

1. Which method reads a file synchronously?



2. Which method adds new content to the end of a file?



3. Which module provides promise-based file operations?