Node.js File System Practice Questions with Solutions

Introduction

The Node.js File System (fs) module allows you to work with files and folders directly from your Node.js application. You can create, read, write, update, rename, and delete files using this built-in module. In this chapter, you will practice the most important fs methods with simple examples. The questions start with basic file operations and gradually move toward practical file-handling tasks. Node.js File System practice questions with solutions help to understand the concepts.

Question 1: How do you create a file using the fs module?

Problem

Create a file named welcome.txt and add a simple message to it.

Solution

const fs = require("fs");

fs.writeFileSync(
    "welcome.txt",
    "Welcome to Node.js!"
);

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

Run:

node app.js

Output

File created successfully.

A new file named welcome.txt will be created.

Its content will be:

Welcome to Node.js!

Step-by-Step Explanation

  1. Import the built-in fs module.
  2. fs stands for File System.
  3. Use writeFileSync() to create the file.
  4. The first argument is the filename.
  5. The second argument is the content.
  6. Node.js creates the file and writes the content.
  7. If the file already exists, its existing content will be replaced.

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

Problem

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

Solution

Make sure welcome.txt contains:

Welcome to Node.js!

Now create app.js:

const fs = require("fs");

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

console.log(data);

Output

Welcome to Node.js!

Step-by-Step Explanation

  1. Import the fs module.
  2. Use readFileSync() to read the file.
  3. Pass the filename.
  4. "utf8" tells Node.js to return readable text.
  5. Store the file content in data.
  6. Display the content using console.log().

Question 3: How do you write new content into an existing file?

Problem

Create a file named student.txt and write student information into it.

Solution

const fs = require("fs");

fs.writeFileSync(
    "student.txt",
    "Name: Riya\nAge: 18\nCourse: Node.js"
);

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

Output

Student information saved.

The student.txt file will contain:

Name: Riya
Age: 18
Course: Node.js

Step-by-Step Explanation

  1. Import fs.
  2. Use writeFileSync().
  3. Provide the filename.
  4. Add the student information.
  5. \n moves the next text to a new line.
  6. Node.js writes the information into the file.

Question 4: How do you add content to an existing file using appendFileSync()?

Problem

Add a new student to an existing students.txt file without deleting its current content.

Solution

Suppose students.txt already contains:

Riya
Aman

Use:

const fs = require("fs");

fs.appendFileSync(
    "students.txt",
    "\nRahul"
);

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

Output

New student added.

The file will now contain:

Riya
Aman
Rahul

Step-by-Step Explanation

  1. Import the fs module.
  2. Use appendFileSync().
  3. Provide the filename.
  4. Provide the new content.
  5. \n starts the new content on a separate line.
  6. Existing content remains unchanged.
  7. The new content is added at the end.

Important Point

writeFileSync() can replace existing content, while appendFileSync() adds content to the end.


Question 5: How do you check whether a file exists?

Problem

Check whether student.txt exists before trying to use it.

Solution

const fs = require("fs");

const fileExists = fs.existsSync("student.txt");

if (fileExists) {
    console.log("Student file exists.");
} else {
    console.log("Student file does not exist.");
}

Output

If the file exists:

Student file exists.

If it does not exist:

Student file does not exist.

Step-by-Step Explanation

  1. Import the fs module.
  2. Use fs.existsSync().
  3. Provide the filename.
  4. The method returns true if the file exists.
  5. Otherwise, it returns false.
  6. Use if...else to display the correct message.

Question 6: How do you rename a file using the fs module?

Problem

Rename oldname.txt to newname.txt.

Solution

const fs = require("fs");

fs.renameSync(
    "oldname.txt",
    "newname.txt"
);

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

Output

File renamed successfully.

Step-by-Step Explanation

  1. Import fs.
  2. Use renameSync().
  3. The first argument is the current filename.
  4. The second argument is the new filename.
  5. Node.js renames the file.
  6. The success message is displayed.

For example:

oldname.txt

becomes:

newname.txt

Question 7: How do you delete a file using fs.unlinkSync()?

Problem

Delete a file named temporary.txt.

Solution

const fs = require("fs");

fs.unlinkSync("temporary.txt");

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

Output

File deleted successfully.

Step-by-Step Explanation

  1. Import the fs module.
  2. Use unlinkSync().
  3. Provide the filename.
  4. Node.js removes the file.
  5. Display the success message.

Important Point

Be careful when using unlinkSync(). The file is deleted from the file system.


Question 8: How do you create a directory using the fs module?

Problem

Create a folder named students.

Solution

const fs = require("fs");

fs.mkdirSync("students");

console.log("Directory created successfully.");

Output

Directory created successfully.

A new folder named students will be created.

Step-by-Step Explanation

  1. Import fs.
  2. Use mkdirSync().
  3. Pass the directory name.
  4. Node.js creates the folder.
  5. Display the success message.

Safer Version

If the directory may already exist, you can use:

const fs = require("fs");

fs.mkdirSync("students", {
    recursive: true
});

console.log("Directory is ready.");

The recursive: true option allows the directory structure to be created without throwing an error simply because the directory already exists.


Question 9: How do you read the files inside a directory?

Problem

Create a folder named documents containing some files and display their names.

Solution

Suppose the folder contains:

documents/
    notes.txt
    report.txt
    data.txt

Create app.js:

const fs = require("fs");

const files = fs.readdirSync("documents");

console.log(files);

Output

The order can vary:

[ 'data.txt', 'notes.txt', 'report.txt' ]

Step-by-Step Explanation

  1. Import the fs module.
  2. Use readdirSync().
  3. Pass the directory name.
  4. Node.js reads the contents of the directory.
  5. The method returns an array containing the directory entries.
  6. Display the array.

This method is useful when you need to find files stored inside a folder.


Question 10: How do you create, write, read, append, and rename a file?

Problem

Create a small file-management program that:

  1. Creates a file.
  2. Writes information.
  3. Reads the information.
  4. Adds more information.
  5. Reads the updated content.
  6. Renames the file.

Solution

const fs = require("fs");

const oldFile = "student.txt";
const newFile = "student-data.txt";

// Step 1: Create and write the file
fs.writeFileSync(
    oldFile,
    "Name: Aarav\nMarks: 85"
);

console.log("File created.");

// Step 2: Read the file
let data = fs.readFileSync(
    oldFile,
    "utf8"
);

console.log("\nOriginal Content:");
console.log(data);

// Step 3: Add more information
fs.appendFileSync(
    oldFile,
    "\nCourse: Node.js"
);

// Step 4: Read updated content
data = fs.readFileSync(
    oldFile,
    "utf8"
);

console.log("\nUpdated Content:");
console.log(data);

// Step 5: Rename the file
fs.renameSync(
    oldFile,
    newFile
);

console.log("\nFile renamed successfully.");

Output

File created.

Original Content:
Name: Aarav
Marks: 85

Updated Content:
Name: Aarav
Marks: 85
Course: Node.js

File renamed successfully.

Step-by-Step Explanation

  1. Import the fs module.
  2. Store the old and new filenames.
  3. Use writeFileSync() to create the file.
  4. Use readFileSync() to read the original content.
  5. Use appendFileSync() to add the course.
  6. Read the file again.
  7. Use renameSync() to rename the file.
  8. Display each stage in the terminal.

This example combines several important fs methods into one small practical application.

Key Takeaways

  • The fs module stands for File System.
  • It is a built-in Node.js module.
  • You can load it using require("fs").
  • writeFileSync() creates or replaces a file.
  • readFileSync() reads file content.
  • appendFileSync() adds content without replacing existing content.
  • existsSync() checks whether a file or directory exists.
  • renameSync() changes a file or directory name.
  • unlinkSync() deletes a file.
  • mkdirSync() creates a directory.
  • readdirSync() reads the contents of a directory.
  • Synchronous methods block the Node.js event loop until the operation finishes.
  • For larger or production applications, asynchronous fs methods are generally preferred.

FAQs

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

The fs module is Node.js’s built-in File System module. It provides methods for working with files and directories.

You can import it using:

const fs = require("fs");

2. Do I need to install the fs module?

No. fs is included with Node.js, so you do not normally install it separately.

const fs = require("fs");

3. What does fs.writeFileSync() do?

writeFileSync() writes data to a file synchronously.

const fs = require("fs");

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

If the file does not exist, it is created. If it already exists, its content is replaced by default.

4. What is the difference between writeFileSync() and appendFileSync()?

writeFileSync() normally replaces the existing file content.

fs.writeFileSync("data.txt", "New content");

appendFileSync() adds new content to the end of the existing file.

fs.appendFileSync("data.txt", "\nMore content");

5. What does fs.readFileSync() do?

readFileSync() reads the contents of a file synchronously.

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

console.log(data);

The "utf8" encoding makes the returned value a readable string.

6. How do you delete a file in Node.js?

You can use fs.unlinkSync() for a synchronous file deletion:

const fs = require("fs");

fs.unlinkSync("data.txt");

Be careful because the file will be removed from the file system.

7. Should I use synchronous or asynchronous fs methods?

Synchronous methods such as readFileSync() are easy to understand and useful for small scripts and learning. In server applications, asynchronous methods are generally preferred because synchronous file operations can block the Node.js event loop while the operation is running.

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

Scroll to Top