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
- Import the built-in
fsmodule. fsstands for File System.- Use
writeFileSync()to create the file. - The first argument is the filename.
- The second argument is the content.
- Node.js creates the file and writes the content.
- 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
- Import the
fsmodule. - Use
readFileSync()to read the file. - Pass the filename.
"utf8"tells Node.js to return readable text.- Store the file content in
data. - 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
- Import
fs. - Use
writeFileSync(). - Provide the filename.
- Add the student information.
\nmoves the next text to a new line.- 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
- Import the
fsmodule. - Use
appendFileSync(). - Provide the filename.
- Provide the new content.
\nstarts the new content on a separate line.- Existing content remains unchanged.
- 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
- Import the
fsmodule. - Use
fs.existsSync(). - Provide the filename.
- The method returns
trueif the file exists. - Otherwise, it returns
false. - Use
if...elseto 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
- Import
fs. - Use
renameSync(). - The first argument is the current filename.
- The second argument is the new filename.
- Node.js renames the file.
- 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
- Import the
fsmodule. - Use
unlinkSync(). - Provide the filename.
- Node.js removes the file.
- 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
- Import
fs. - Use
mkdirSync(). - Pass the directory name.
- Node.js creates the folder.
- 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
- Import the
fsmodule. - Use
readdirSync(). - Pass the directory name.
- Node.js reads the contents of the directory.
- The method returns an array containing the directory entries.
- 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:
- Creates a file.
- Writes information.
- Reads the information.
- Adds more information.
- Reads the updated content.
- 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
- Import the
fsmodule. - Store the old and new filenames.
- Use
writeFileSync()to create the file. - Use
readFileSync()to read the original content. - Use
appendFileSync()to add the course. - Read the file again.
- Use
renameSync()to rename the file. - Display each stage in the terminal.
This example combines several important fs methods into one small practical application.
Key Takeaways
- The
fsmodule 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
fsmethods 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.
