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
- Import the
fsmodule. - Use
writeFileSync()to write data. - Pass the filename as the first argument.
- Pass the text as the second argument.
- Node.js creates the file if it does not exist.
- 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
- Import the
fsmodule. - Use
readFileSync(). - Pass the filename.
- Use
"utf8"so Node.js returns the file as text. - Store the content in
data. - 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
- Import
fs. - Use
appendFileSync(). - Specify the existing filename.
- Add the new content.
\nmoves the new text to a new line.- 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
- Import the
fsmodule. - Call
fs.writeFile(). - Provide the filename.
- Provide the content.
- Specify
"utf8"encoding. - Provide a callback function.
- If an error occurs,
errorcontains information about it. - 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
- Import
fs. - Use
readFile(). - Provide the filename.
- Specify
"utf8". - Provide a callback.
- If an error occurs, display it.
- Otherwise,
datacontains the file content. - 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
- Create a JavaScript object.
- Use
JSON.stringify()to convert the object into JSON text. - Write the JSON text to
student.json. - Read the file using
readFileSync(). - Use
JSON.parse()to convert the JSON text back into a JavaScript object. - 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
- Import
fs. - Read
source.txt. - Store its content in
data. - Create or replace
backup.txt. - Write the same data into
backup.txt. - 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
- Read the complete file.
- Store the content in
data. - Use
split("\n")to divide the text at line breaks. - The result is an array.
- Use
forEach()to process each line. - 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
- Create
result.txt. - Write the original marks.
- Use
writeFileSync()again. - The previous content is replaced.
- Write the updated marks.
- Read the file.
- 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
- Create an array containing student objects.
- Use
JSON.stringify()to convert the array into JSON. - Save the JSON data using
writeFileSync(). - Read the file using
readFileSync(). - Convert the JSON text back into an array using
JSON.parse(). - Use
forEach()to go through each student. - 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
fsmodule 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.
