Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

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.

Remember: Updating a task in JavaScript memory does not automatically update 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.

todos.json
[
    {
        "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

JavaScript
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

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.

Important: This example changes only the in-memory array. To keep the new task after the application stops, save the array to 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

JavaScript
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

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

JavaScript
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

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.

1. Read File

fs.readFile()

↓
2. Parse JSON

JSON.parse()

↓
3. Modify Task Array

Add a task or update an existing task

↓
4. Save JSON

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

JavaScript
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

Terminal
node updateTodo.js

Step 4: Expected Output

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.

Updated todos.json
[
    {
        "id": 1,
        "title": "Learn Node.js",
        "completed": true
    },
    {
        "id": 2,
        "title": "Practice JavaScript",
        "completed": true
    }
]
Important: This example overwrites 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.