Reading todos.json in Node.js
Learn how to read task data from a JSON file using the Node.js File System module and display saved tasks in a CLI application.
In this tutorial, we will use the fs module to
read todos.json, convert JSON text into JavaScript
data, and display the saved tasks in the terminal.
1. What Does Reading todos.json Mean?
A JSON file stores data in a structured text format. In our
Task Manager project, todos.json stores the tasks
created by the user.
Reading todos.json means opening the file,
retrieving its contents, converting the JSON text into
JavaScript data, and using that data in our application.
For example, if the file contains a task named Learn Node.js, our application can read that task and display it in the terminal.
fs.readFile() reads file contents as a string
when an encoding such as "utf8" is provided.
JSON.parse() converts valid JSON text into
JavaScript data.
2. Required Node.js Modules and Methods
We will use the built-in File System module and the
JSON.parse() method to read our task data.
| Method or Module | Simple Explanation | Responsibility |
|---|---|---|
| fs | Node.js File System module. | Provides methods to work with files. |
| fs.readFile() | Reads a file asynchronously. | Retrieves the contents of todos.json. |
| JSON.parse() | Converts JSON text into JavaScript data. | Creates an array or object from valid JSON. |
| Array.forEach() | Processes each array element. | Helps display each saved task. |
| console.log() | Displays information in the terminal. | Shows task details to the user. |
3. Reading todos.json Diagram
This diagram shows how task information moves from the JSON file to the terminal.
todos.json
Contains saved task data
fs.readFile()
Reads JSON text from the file
JSON.parse()
Converts JSON text into a JavaScript array
Terminal Output
Displays the saved tasks
Note: The file must contain valid JSON before it can be parsed.
4. Create todos.json
First, create a file named todos.json in your
Task Manager project folder. Add the following sample data.
[
{
"id": 1,
"title": "Learn Node.js",
"completed": false
},
{
"id": 2,
"title": "Practice JavaScript",
"completed": true
},
{
"id": 3,
"title": "Build Task Manager",
"completed": false
}
]
Understanding the Data
The JSON file contains an array with three task objects.
Each object has an id, a title,
and a completed property.
ididentifies a task.titlestores the task name.-
completedstores the task status as a Boolean value.
true and false
must not be enclosed in quotes.
5. Read todos.json Using fs.readFile()
The fs.readFile() method reads a file
asynchronously. It uses a callback function to handle
the result or an error.
Step 1: Create app.js
Create or open app.js in the same folder
as todos.json.
Step 2: Write the Program
const fs = require("node:fs");
fs.readFile("todos.json", "utf8", (err, data) => {
if (err) {
console.log("Error reading todos.json:", err.message);
return;
}
const todos = JSON.parse(data);
console.log("Saved Tasks:");
console.log(todos);
});
Step 3: Run the Program
node app.js
Step 4: Expected Output
Saved Tasks:
[
{ id: 1, title: 'Learn Node.js', completed: false },
{ id: 2, title: 'Practice JavaScript', completed: true },
{ id: 3, title: 'Build Task Manager', completed: false }
]
Step 5: Understand the Code
-
require("node:fs")loads the built-in File System module. -
fs.readFile()reads the contents of todos.json. -
"utf8"tells Node.js to provide the file contents as text. -
if (err)checks whether the file-reading operation failed. -
JSON.parse(data)converts the JSON text into an array. -
console.log(todos)displays the parsed task data.
JSON.parse() throws an error.
The next example handles both types of errors.
6. Display Tasks One by One
Instead of displaying the complete array, we can use
forEach() to display each task in a readable format.
Program
const fs = require("node:fs");
fs.readFile("todos.json", "utf8", (err, data) => {
if (err) {
console.log("Error reading file:", err.message);
return;
}
let todos;
try {
todos = JSON.parse(data);
} catch (error) {
console.log("Invalid JSON data in todos.json.");
return;
}
if (!Array.isArray(todos)) {
console.log("The JSON data must be an array.");
return;
}
if (todos.length === 0) {
console.log("No tasks found.");
return;
}
console.log("===== TASK MANAGER =====");
todos.forEach((todo) => {
const status = todo.completed ? "Completed" : "Pending";
console.log(
todo.id + ". " + todo.title + " - " + status
);
});
});
Expected Output
===== TASK MANAGER =====
1. Learn Node.js - Pending
2. Practice JavaScript - Completed
3. Build Task Manager - Pending
Explanation
The program first reads the file and checks for errors.
It then parses the JSON inside a try...catch
block so invalid JSON can be handled safely.
The Array.isArray() method checks that the parsed
data is an array. The forEach() method processes
each task, and the conditional expression displays
Completed or Pending
according to the task's status.
7. Handling Common Errors
A CLI application should handle missing files and invalid JSON instead of terminating unexpectedly.
| Error | Possible Reason | Solution |
|---|---|---|
| ENOENT | todos.json does not exist at the specified path. | Create the file or correct its path. |
| SyntaxError | The file contains invalid JSON. | Correct the JSON syntax and quotes. |
| Empty task list | The JSON file contains an empty array. | Display a message that no tasks were found. |
| Unexpected data structure | The JSON contains an object instead of an array. | Validate the parsed data using Array.isArray(). |
fs.readFile() errors and
JSON.parse() errors are different. Handle
the file operation first, then validate and parse its contents.
8. Complete Data Flow
The following diagram summarizes the complete process of reading and displaying saved tasks.
fs.readFile()
JSON.parse() and array validation
forEach() and console.log()
9. Practice Task
Task: Read and Display Student Tasks
Create a JSON file containing at least three task objects. Each object should contain an ID, title, and completion status.
Write a Node.js program that reads the file, parses its contents, and displays each task on a separate line.
Expected Output Format
===== MY TASKS =====
1. Complete JavaScript Practice - Pending
2. Learn File System Module - Completed
3. Create CLI Project - Pending
Challenge: Handle a missing file, invalid JSON, and an empty array without allowing the application to crash unexpectedly.
Important Points
-
Use
fs.readFile()to read a file asynchronously. -
Use the
"utf8"encoding to receive text. -
Use
JSON.parse()to convert valid JSON text into JavaScript data. - Handle file-reading errors and JSON parsing errors separately.
- Validate that the parsed data has the expected structure.
-
Use
forEach()to display each task individually.
Summary
In this tutorial, we learned how to read task data from todos.json using the Node.js File System module. We used fs.readFile() to retrieve the file contents, JSON.parse() to convert JSON text into JavaScript data, and forEach() to display tasks in the terminal. We also learned how to handle missing files, invalid JSON, and empty task lists. These concepts prepare us to update task data and save changes in our CLI Task Manager project.