Node.js Reading and Writing Files Practice Questions with Solutions

Introduction

Reading and writing files is an essential skill in Node.js. The built-in fs module provides several methods for storing and retrieving data from files. In this chapter, you will practice reading and writing text files using both synchronous and asynchronous approaches. The examples start with simple file operations and gradually introduce callbacks, promises, JSON files, and practical file-handling tasks. Node.js Reading and Writing Files Practice Questions with Solutions help to understand the concepts.

Question 1: How do you write text to a file using writeFileSync()?

Problem

Create a file named message.txt and write a welcome message into it.

Solution

const fs = require("fs");

fs.writeFileSync(
    "message.txt",
    "Welcome to Node.js file handling!"
);

console.log("Data written successfully.");

Output

Data written successfully.

The message.txt file will contain:

Welcome to Node.js file handling!

Step-by-Step Explanation

  1. Import the fs module.
  2. Use writeFileSync() to write data.
  3. Pass the filename as the first argument.
  4. Pass the text as the second argument.
  5. Node.js creates the file if it does not exist.
  6. If the file already exists, its content is replaced by default.

Question 2: How do you read a text file using readFileSync()?

Problem

Read the content of message.txt and display it in the terminal.

Solution

const fs = require("fs");

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

console.log(data);

Output

Welcome to Node.js file handling!

Step-by-Step Explanation

  1. Import the fs module.
  2. Use readFileSync().
  3. Pass the filename.
  4. Use "utf8" so Node.js returns the file as text.
  5. Store the content in data.
  6. Display the content.

Without specifying an encoding, Node.js returns a Buffer object.


Question 3: How do you append data to an existing file?

Problem

Add a second line to message.txt without deleting its existing content.

Solution

const fs = require("fs");

fs.appendFileSync(
    "message.txt",
    "\nKeep practicing Node.js!"
);

console.log("New content added.");

Output

New content added.

The file will now contain:

Welcome to Node.js file handling!
Keep practicing Node.js!

Step-by-Step Explanation

  1. Import fs.
  2. Use appendFileSync().
  3. Specify the existing filename.
  4. Add the new content.
  5. \n moves the new text to a new line.
  6. Existing content remains unchanged.

Question 4: How do you write to a file asynchronously?

Problem

Write a message to async-message.txt using the asynchronous writeFile() method.

Solution

const fs = require("fs");

fs.writeFile(
    "async-message.txt",
    "Hello from asynchronous Node.js!",
    "utf8",
    (error) => {
        if (error) {
            console.log("Error:", error);
            return;
        }

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

Output

File written successfully.

Step-by-Step Explanation

  1. Import the fs module.
  2. Call fs.writeFile().
  3. Provide the filename.
  4. Provide the content.
  5. Specify "utf8" encoding.
  6. Provide a callback function.
  7. If an error occurs, error contains information about it.
  8. Otherwise, the success message is displayed.

Important Point

writeFile() is asynchronous. Node.js can continue handling other work while the file operation is being completed.


Question 5: How do you read a file asynchronously?

Problem

Read async-message.txt using fs.readFile().

Solution

const fs = require("fs");

fs.readFile(
    "async-message.txt",
    "utf8",
    (error, data) => {
        if (error) {
            console.log("Error:", error);
            return;
        }

        console.log(data);
    }
);

Output

Hello from asynchronous Node.js!

Step-by-Step Explanation

  1. Import fs.
  2. Use readFile().
  3. Provide the filename.
  4. Specify "utf8".
  5. Provide a callback.
  6. If an error occurs, display it.
  7. Otherwise, data contains the file content.
  8. Print the content.

The callback receives:

(error, data)

The first value represents an error, and the second contains the file data when the operation succeeds.


Question 6: How do you write and read a JSON file?

Problem

Store student information in a JSON file and then read it back into Node.js.

Solution

const fs = require("fs");

const student = {
    name: "Riya",
    age: 18,
    course: "Node.js"
};

// Convert object into JSON text
const jsonData = JSON.stringify(student, null, 2);

// Write JSON data
fs.writeFileSync(
    "student.json",
    jsonData
);

// Read JSON data
const data = fs.readFileSync(
    "student.json",
    "utf8"
);

// Convert JSON text back into object
const result = JSON.parse(data);

console.log(result);

Output

{
  name: 'Riya',
  age: 18,
  course: 'Node.js'
}

The student.json file will contain:

{
  "name": "Riya",
  "age": 18,
  "course": "Node.js"
}

Step-by-Step Explanation

  1. Create a JavaScript object.
  2. Use JSON.stringify() to convert the object into JSON text.
  3. Write the JSON text to student.json.
  4. Read the file using readFileSync().
  5. Use JSON.parse() to convert the JSON text back into a JavaScript object.
  6. Display the object.

This technique is commonly used when storing structured data in files.


Question 7: How do you copy the contents of one file into another file?

Problem

Read source.txt and create backup.txt containing the same content.

Solution

const fs = require("fs");

const data = fs.readFileSync(
    "source.txt",
    "utf8"
);

fs.writeFileSync(
    "backup.txt",
    data
);

console.log("File copied successfully.");

Output

File copied successfully.

Step-by-Step Explanation

  1. Import fs.
  2. Read source.txt.
  3. Store its content in data.
  4. Create or replace backup.txt.
  5. Write the same data into backup.txt.
  6. Both files now contain the same text.

Example

If source.txt contains:

Node.js is powerful.

then backup.txt will contain:

Node.js is powerful.

Question 8: How do you read a file line by line?

Problem

Read a text file and display each line separately.

Solution

Suppose students.txt contains:

Riya
Aman
Rahul
Priya

Create app.js:

const fs = require("fs");

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

const students = data.split("\n");

students.forEach((student) => {
    console.log(student);
});

Output

Riya
Aman
Rahul
Priya

Step-by-Step Explanation

  1. Read the complete file.
  2. Store the content in data.
  3. Use split("\n") to divide the text at line breaks.
  4. The result is an array.
  5. Use forEach() to process each line.
  6. Print each student separately.

Important Note

Line endings can differ between operating systems. For simple learning examples, split("\n") is fine. In more robust code, line-ending handling may need additional care.


Question 9: How do you update existing file content?

Problem

Create a file containing a student’s marks and update the marks later.

Solution

const fs = require("fs");

// Original information
fs.writeFileSync(
    "result.txt",
    "Student: Aarav\nMarks: 70"
);

// Updated information
fs.writeFileSync(
    "result.txt",
    "Student: Aarav\nMarks: 90"
);

const data = fs.readFileSync(
    "result.txt",
    "utf8"
);

console.log(data);

Output

Student: Aarav
Marks: 90

Step-by-Step Explanation

  1. Create result.txt.
  2. Write the original marks.
  3. Use writeFileSync() again.
  4. The previous content is replaced.
  5. Write the updated marks.
  6. Read the file.
  7. Display the updated information.

Important Point

writeFileSync() replaces the existing content unless you use an appropriate flag or choose an append operation.


Question 10: How do you create a small file-based student record system?

Problem

Create a simple program that:

  • Stores student information.
  • Saves it to a JSON file.
  • Reads the JSON file.
  • Displays student details.

Solution

const fs = require("fs");

const students = [
    {
        name: "Aarav",
        marks: 85
    },
    {
        name: "Riya",
        marks: 92
    },
    {
        name: "Rahul",
        marks: 76
    }
];

// Convert array into JSON
const jsonData = JSON.stringify(
    students,
    null,
    2
);

// Write data to file
fs.writeFileSync(
    "students.json",
    jsonData
);

console.log("Student data saved.");

// Read data from file
const fileData = fs.readFileSync(
    "students.json",
    "utf8"
);

// Convert JSON into JavaScript array
const data = JSON.parse(fileData);

console.log("\nStudent Records:");

data.forEach((student) => {
    console.log(
        `${student.name} - ${student.marks} marks`
    );
});

Output

Student data saved.

Student Records:
Aarav - 85 marks
Riya - 92 marks
Rahul - 76 marks

The students.json file will contain:

[
  {
    "name": "Aarav",
    "marks": 85
  },
  {
    "name": "Riya",
    "marks": 92
  },
  {
    "name": "Rahul",
    "marks": 76
  }
]

Step-by-Step Explanation

  1. Create an array containing student objects.
  2. Use JSON.stringify() to convert the array into JSON.
  3. Save the JSON data using writeFileSync().
  4. Read the file using readFileSync().
  5. Convert the JSON text back into an array using JSON.parse().
  6. Use forEach() to go through each student.
  7. Display the name and marks.

This is a simple example of how files can be used to store structured application data.

Key Takeaways

  • The Node.js fs module provides file-reading and file-writing functionality.
  • writeFileSync() writes data to a file synchronously.
  • readFileSync() reads file content synchronously.
  • appendFileSync() adds new content to an existing file.
  • writeFile() performs asynchronous file writing.
  • readFile() performs asynchronous file reading.
  • "utf8" can be used to read text as a string.
  • JSON.stringify() converts JavaScript data into JSON text.
  • JSON.parse() converts JSON text back into JavaScript data.
  • writeFileSync() normally replaces existing file content.
  • appendFileSync() preserves existing content and adds new content.
  • Asynchronous file operations are generally preferred in Node.js server applications because synchronous operations can block the event loop.
  • Reading and writing JSON files is useful for simple data-storage applications.

FAQs

1. How do you read a file in Node.js?

You can use fs.readFileSync() for synchronous reading:

const fs = require("fs");

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

console.log(data);

You can also use asynchronous fs.readFile().

2. How do you write a file in Node.js?

You can use fs.writeFileSync():

const fs = require("fs");

fs.writeFileSync(
    "data.txt",
    "Hello Node.js!"
);

For asynchronous writing, use fs.writeFile().

3. What is the difference between readFile() and readFileSync()?

readFile() is asynchronous and uses a callback.

fs.readFile("data.txt", "utf8", (error, data) => {
    // Handle result
});

readFileSync() is synchronous and waits for the operation to finish.

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

4. What does utf8 mean when reading a file?

utf8 is a text encoding. When you provide "utf8" to a file-reading method, Node.js returns the file content as a readable string rather than a Buffer.

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

5. How do I add content without deleting existing file data?

Use appendFile() or appendFileSync().

const fs = require("fs");

fs.appendFileSync(
    "data.txt",
    "\nNew information"
);

The existing content remains and the new content is added at the end.

6. How can I read and write JSON files in Node.js?

Use JSON.stringify() before writing and JSON.parse() after reading.

const json = JSON.stringify(data);

fs.writeFileSync("data.json", json);

const fileData = fs.readFileSync(
    "data.json",
    "utf8"
);

const result = JSON.parse(fileData);

7. Should I use synchronous file operations in a Node.js server?

For simple scripts and learning, synchronous methods are easy to understand. In Node.js server applications, asynchronous methods are generally preferred because synchronous file operations can block the event loop while the file operation is running.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top