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

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.

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

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

  • id identifies a task.
  • title stores the task name.
  • completed stores the task status as a Boolean value.
Important: JSON uses double quotes around property names and string values. Boolean values such as 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

JavaScript
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

Terminal
node app.js

Step 4: Expected Output

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

  1. require("node:fs") loads the built-in File System module.
  2. fs.readFile() reads the contents of todos.json.
  3. "utf8" tells Node.js to provide the file contents as text.
  4. if (err) checks whether the file-reading operation failed.
  5. JSON.parse(data) converts the JSON text into an array.
  6. console.log(todos) displays the parsed task data.
Remember: Always handle file-reading errors. Also, if the file contains invalid JSON, 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

JavaScript
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

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

Start the CLI Application
↓
Read todos.json

fs.readFile()

↓
Parse and Validate JSON

JSON.parse() and array validation

↓
Display Tasks

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
Output
===== 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.