Updating Todos in Node.js
Learn how to add new tasks, update existing task details, and change task status in a JSON-based Node.js CLI Task Manager.
In this tutorial, we will read tasks from
todos.json, modify the task array using JavaScript,
and prepare the updated data for saving back to the file.
1. What Does Updating Todos Mean?
Updating todos means changing information in the task list. For example, we may add a new task, change a task title, or mark a task as completed.
In our Task Manager project, tasks are stored as objects inside an array. We can use JavaScript array methods and object properties to modify those tasks.
todos.json. We must save the updated array
to the file separately.
2. Common Task Update Operations
| Operation | Purpose | Example |
|---|---|---|
| Add Task | Adds a new task to the array. | todos.push(newTodo) |
| Update Title | Changes an existing task's title. | todo.title = "New Title" |
| Mark Completed | Changes the task status. | todo.completed = true |
| Find Task | Finds a task using its ID. | todos.find() |
| Save Changes | Writes updated data to the JSON file. | fs.writeFile() |
3. Task Update Process Diagram
The following diagram shows how the application updates task information.
Read todos.json
Load the saved task data
Find the Task
Search using the task ID
Update Task Data
Change the title or completion status
Save Updated Data
Write the new JSON data to the file
Note: This is the general flow. Each file operation must handle errors before the next step continues.
4. Prepare todos.json
Before updating tasks, create or open
todos.json and add the following sample data.
[
{
"id": 1,
"title": "Learn Node.js",
"completed": false
},
{
"id": 2,
"title": "Practice JavaScript",
"completed": true
}
]
The file contains two tasks. We will use these tasks to understand how to add new tasks and modify existing tasks.
5. Add a New Task Using push()
The push() method adds a new element to the end
of an array. We can use it to add a new task to the task list.
Example
const todos = [
{ id: 1, title: "Learn Node.js", completed: false },
{ id: 2, title: "Practice JavaScript", completed: true }
];
const newTodo = {
id: 3,
title: "Build Task Manager",
completed: false
};
todos.push(newTodo);
console.log(todos);
Output
[
{ id: 1, title: 'Learn Node.js', completed: false },
{ id: 2, title: 'Practice JavaScript', completed: true },
{ id: 3, title: 'Build Task Manager', completed: false }
]
Explanation:
The newTodo object contains the details of a new
task. The push() method adds this object to the
end of the todos array.
todos.json.
6. Update an Existing Task Title
The find() method returns the first element
that matches a condition. We can find a task using its ID
and update its title.
Example
const todos = [
{ id: 1, title: "Learn Node.js", completed: false },
{ id: 2, title: "Practice JavaScript", completed: true }
];
const todo = todos.find((item) => item.id === 1);
if (todo) {
todo.title = "Learn Node.js File System";
console.log("Task title updated successfully.");
} else {
console.log("Task not found.");
}
console.log(todos);
Output
Task title updated successfully.
[
{ id: 1, title: 'Learn Node.js File System', completed: false },
{ id: 2, title: 'Practice JavaScript', completed: true }
]
Explanation: The program searches for the task with ID 1. If the task exists, its title is changed. If no matching task is found, the program displays a message.
7. Mark a Task as Completed
Each task has a completed property. We can
change its value from false to
true when the user finishes the task.
Example
const todos = [
{ id: 1, title: "Learn Node.js", completed: false },
{ id: 2, title: "Practice JavaScript", completed: false }
];
const todo = todos.find((item) => item.id === 2);
if (todo) {
todo.completed = true;
console.log("Task marked as completed.");
} else {
console.log("Task not found.");
}
console.log(todos);
Output
Task marked as completed.
[
{ id: 1, title: 'Learn Node.js', completed: false },
{ id: 2, title: 'Practice JavaScript', completed: true }
]
Explanation:
The program finds task ID 2 and changes its
completed property to true.
The second task is now marked as completed in the array.
8. Read, Update, and Save Workflow
A real Task Manager must save the modified array to the JSON file. This diagram shows the complete process.
fs.readFile()
JSON.parse()
Add a task or update an existing task
fs.writeFile()
9. Practical Program: Update and Save a Task
Now let's create a complete example that reads
todos.json, updates a task's status, and saves
the changes back to the same file.
Step 1: Check todos.json
Make sure todos.json contains an array of task
objects, such as the sample data shown earlier.
Step 2: Create updateTodo.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 todo = todos.find((item) => item.id === 1);
if (!todo) {
console.log("Task with ID 1 was not found.");
return;
}
todo.completed = true;
const updatedData = JSON.stringify(todos, null, 4);
fs.writeFile("todos.json", updatedData, "utf8", (writeErr) => {
if (writeErr) {
console.log("Error saving todos.json:", writeErr.message);
return;
}
console.log("Task updated and saved successfully.");
console.log(todo);
});
});
Step 3: Run the Program
node updateTodo.js
Step 4: Expected Output
Task updated and saved successfully.
{ id: 1, title: 'Learn Node.js', completed: true }
Step 5: Check todos.json
After the program runs successfully, open
todos.json. The task with ID 1 should now
have "completed": true.
[
{
"id": 1,
"title": "Learn Node.js",
"completed": true
},
{
"id": 2,
"title": "Practice JavaScript",
"completed": true
}
]
todos.json with the
updated array. Test it using sample data or a backup of your
file. The task ID must exist for the update to occur.
10. Important Methods Used
| Method | Purpose |
|---|---|
Array.push() |
Adds a new task to the array. |
Array.find() |
Finds a task matching a condition. |
JSON.parse() |
Converts JSON text into JavaScript data. |
JSON.stringify() |
Converts JavaScript data into JSON text. |
fs.readFile() |
Reads the saved task data. |
fs.writeFile() |
Writes the updated data to the file. |
11. Practice Tasks
Task 1: Update a Task Title
Find a task using its ID and change its title to
Practice Node.js Daily.
Hint:
Use find() to locate the task and then
assign a new value to its title property.
Task 2: Add and Save a New Task
Read todos.json, add a new task with a unique
ID, title, and completion status, and save the updated array.
Hint:
Use push() to add the task and
JSON.stringify() with fs.writeFile()
to save the data.
Important Points
-
Use
push()to add a new task to an array. -
Use
find()to locate a task by its ID. - Change object properties to update task details.
-
Use
JSON.stringify()to prepare JSON text for saving. -
Use
fs.writeFile()to persist changes to the file. - Handle reading, parsing, and writing errors carefully.
Summary
In this tutorial, we learned how to update tasks in a Node.js CLI Task Manager. We used push() to add tasks, find() to locate an existing task, and object properties to update titles and completion status. We also learned how to read todos.json, parse its contents, convert the modified array back into JSON using JSON.stringify(), and save the changes using fs.writeFile(). These concepts prepare us to build a complete task management workflow.