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

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.

Remember: 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

JavaScript
const todo = {
    id: 1,
    title: "Learn Node.js",
    completed: false
};

const jsonData = JSON.stringify(todo, null, 4);

console.log(jsonData);

Output

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.

Remember: The indentation argument makes JSON easier to read. It does not change the meaning of the stored data.

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

JavaScript
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

Terminal
node app.js

Expected Output

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.

Important: This example replaces the existing file contents with the two tasks in the array. Use a test file or back up important data before running it.

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.

todos.json
[
    {
        "id": 1,
        "title": "Learn Node.js",
        "completed": false
    }
]

Step 2: Create saveTodo.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 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

Terminal
node saveTodo.js

Expected Output

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.

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

1. Read Existing Tasks

fs.readFile()

↓
2. Convert JSON to JavaScript

JSON.parse()

↓
3. Modify the Task Array

Add or update a task

↓
4. Convert Back to JSON

JSON.stringify()

↓
5. Save the File

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.
Important: 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.