Saving Todos to JSON in Node.js
Learn how to save task information permanently in a JSON file using the Node.js File System module.
In this tutorial, we will convert JavaScript task data into
JSON text and save it in todos.json using
fs.writeFile(). We will also handle errors and
verify that the updated data is stored correctly.
1. What Does Saving Todos to JSON Mean?
Saving todos means writing the current task list to a file so that the information remains available after the Node.js application stops running.
JavaScript stores our tasks in an array of objects while the
application is running. To save those tasks in
todos.json, we convert the array into JSON text
and write that text to the file.
JSON.stringify() converts JavaScript data into
JSON text, while fs.writeFile() writes that text
to a file.
2. Important Methods for Saving JSON
| Method | Simple Explanation | Purpose |
|---|---|---|
| JSON.stringify() | Converts JavaScript data into JSON text. | Prepares the task array for saving. |
| fs.writeFile() | Writes data to a file asynchronously. | Saves the task data in todos.json. |
| fs.readFile() | Reads file contents. | Retrieves saved tasks when needed. |
| JSON.parse() | Converts JSON text into JavaScript data. | Restores the task array from the file. |
3. Saving Todos Diagram
The following diagram explains how task information is converted and saved to a JSON file.
JavaScript Array
Contains task objects
JSON.stringify()
Converts the array into JSON text
fs.writeFile()
Writes JSON text to the file
todos.json
Stores the saved task information
Note: The application should confirm success only after the file-writing callback reports that the write completed.
4. What Is JSON.stringify()?
JSON.stringify() is a JavaScript method that
converts a JavaScript value, such as an array or object,
into a JSON string.
Example
const todo = {
id: 1,
title: "Learn Node.js",
completed: false
};
const jsonData = JSON.stringify(todo, null, 4);
console.log(jsonData);
Output
{
"id": 1,
"title": "Learn Node.js",
"completed": false
}
Understanding the Arguments
In JSON.stringify(todo, null, 4), the first
argument is the value to convert, the second argument is
the replacer (here, null means no filtering),
and the third argument specifies four spaces for indentation.
5. Save Data Using fs.writeFile()
The fs.writeFile() method writes data to a file
asynchronously. If the file already exists, its contents
are replaced by default. If the file does not exist, Node.js
normally creates it.
Example
const fs = require("node:fs");
const todos = [
{
id: 1,
title: "Learn Node.js",
completed: false
},
{
id: 2,
title: "Practice JavaScript",
completed: true
}
];
const jsonData = JSON.stringify(todos, null, 4);
fs.writeFile("todos.json", jsonData, "utf8", (err) => {
if (err) {
console.log("Error saving todos:", err.message);
return;
}
console.log("Todos saved successfully.");
});
Run the Program
node app.js
Expected Output
Todos saved successfully.
Explanation:
First, the task array is converted into JSON text.
Then fs.writeFile() writes the text to
todos.json. The success message appears only
if no write error is reported.
6. Practical Program: Add and Save a New Todo
Now let's build a practical example that reads the existing
tasks, adds a new task, and saves the complete array back
to todos.json.
Step 1: Prepare todos.json
Create todos.json with the following initial data.
[
{
"id": 1,
"title": "Learn Node.js",
"completed": false
}
]
Step 2: Create saveTodo.js
const fs = require("node:fs");
fs.readFile("todos.json", "utf8", (err, data) => {
if (err) {
console.log("Error reading todos.json:", 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;
}
const newTodo = {
id: Date.now(),
title: "Build a CLI Task Manager",
completed: false
};
todos.push(newTodo);
const updatedData = JSON.stringify(todos, null, 4);
fs.writeFile("todos.json", updatedData, "utf8", (writeErr) => {
if (writeErr) {
console.log("Error saving todos:", writeErr.message);
return;
}
console.log("New todo saved successfully.");
console.log(newTodo);
});
});
Step 3: Run the Program
node saveTodo.js
Expected Output
New todo saved successfully.
{
id: 1792152000000,
title: 'Build a CLI Task Manager',
completed: false
}
The example ID above is illustrative. The actual ID is generated
using Date.now(), so its value will depend on when
the program runs.
Step 4: Verify todos.json
Open todos.json after the program finishes.
The file should contain the original task and the newly added task.
[
{
"id": 1,
"title": "Learn Node.js",
"completed": false
},
{
"id": 1792152000000,
"title": "Build a CLI Task Manager",
"completed": false
}
]
The second task's ID will differ when you run the program.
7. Complete Read and Save Workflow
A task management application must read existing data before modifying it, so previous tasks are not accidentally lost.
fs.readFile()
JSON.parse()
Add or update a task
JSON.stringify()
fs.writeFile()
8. Common Errors While Saving JSON
| Error or Problem | Possible Reason | Solution |
|---|---|---|
| ENOENT | The directory or file path is incorrect. | Check the file path and create the required directory. |
| EACCES | The process does not have permission to write. | Check file and directory permissions. |
| Invalid JSON | The original JSON text cannot be parsed. | Validate the file contents before updating. |
| Old data disappears | The file was overwritten with a smaller data array. | Read existing data before making changes. |
fs.writeFile() replaces the file contents by default.
If you want to preserve existing tasks, read them first and
write back the complete updated array.
9. Practice Tasks
Task 1: Save Three Todos
Create an array containing three task objects and save it
to todos.json using fs.writeFile().
Hint:
Convert the array using JSON.stringify(todos, null, 4).
Task 2: Add and Save a Todo
Read the existing task array, add one new task, and save the updated array without removing previous tasks.
Challenge: Handle missing files, invalid JSON, and write errors appropriately.
Important Points
-
Use
JSON.stringify()to convert JavaScript data into JSON text. -
Use
fs.writeFile()to save the data asynchronously. - Check the callback error before reporting a successful save.
- Read existing tasks before adding or updating them.
- By default, writing a file replaces its previous contents.
- Validate JSON data and handle file-system errors.
Summary
In this tutorial, we learned how to save task data in a JSON file using Node.js. We used JSON.stringify() to convert JavaScript arrays into JSON text and fs.writeFile() to write the data to todos.json. We also created a practical program that reads existing tasks, adds a new task, and saves the complete updated array. Proper error handling helps ensure that file operations report failures clearly and that previous task data is not accidentally lost.