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 Files in Node.js

Reading files is one of the most common operations in Node.js. The File System module provides methods that allow us to read information stored in text files, JSON files, and other supported file formats.

In this lesson, we will learn how to read files using fs.readFile() and fs.readFileSync(), understand UTF-8 encoding, handle errors, and display file content in the terminal.


1. What Does Reading a File Mean?

Reading a file means retrieving the information already stored inside a file. A Node.js application can read a file and use its content for further processing.

For example, suppose a file named student.txt contains student information. We can read that file and display the information in the terminal.

student.txt

Name: Rahul

Course: Node.js

↓
Node.js Application

Reads the file using the fs module

↓
Terminal Output

Name: Rahul

Course: Node.js

2. The fs.readFile() Method

The fs.readFile() method reads a file asynchronously. This means Node.js can continue executing other JavaScript code while the file operation is being handled.

Syntax:

JavaScript
fs.readFile(path, encoding, callback);

Parameters:

Parameter Meaning
path The path of the file to read.
encoding Specifies how file content should be decoded, such as UTF-8. It is optional.
callback A function that receives the error, if any, and the file data.

The callback follows the error-first pattern: (err, data). If an error occurs, err contains the error information. Otherwise, data contains the file content.

3. First Example: Read a Text File

Let's create a simple Node.js application that reads a text file and displays its content.

Step 1: Create a Project Folder

Terminal
mkdir ReadingFilesDemo
cd ReadingFilesDemo
npm init -y

Step 2: Create message.txt

Create a file named message.txt in the project folder and add the following content.

message.txt
Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute

Step 3: Create app.js

app.js
const fs = require("fs");

fs.readFile("message.txt", "utf8", (err, data) => {
    if (err) {
        console.log("Error reading file:", err.message);
        return;
    }

    console.log("File Content:");
    console.log(data);
});

Step 4: Run the Program

Terminal
node app.js

Output:

File Content:
Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute

Explanation:

  • require("fs") imports the File System module.
  • "message.txt" specifies the file to read.
  • "utf8" converts the file content into a readable string.
  • (err, data) receives the error and file content.
  • console.log(data) displays the content in the terminal.

4. Why Do We Use UTF-8 Encoding?

When Node.js reads a file without specifying an encoding, the returned content is normally a Buffer. A Buffer represents binary data.

If we want to work with ordinary text, we can specify "utf8" as the encoding.

Example Without Encoding

app.js
const fs = require("fs");

fs.readFile("message.txt", (err, data) => {
    if (err) {
        console.log(err.message);
        return;
    }

    console.log(data);
    console.log("Is Buffer:", Buffer.isBuffer(data));
});

Example output:

<Buffer 57 65 6c 63 6f 6d 65 ...>
Is Buffer: true

The exact Buffer output depends on the content of the file.

Example With UTF-8 Encoding

app.js
const fs = require("fs");

fs.readFile("message.txt", "utf8", (err, data) => {
    if (err) {
        console.log(err.message);
        return;
    }

    console.log(data);
    console.log("Is Buffer:", Buffer.isBuffer(data));
});

Output:

Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute
Is Buffer: false
Remember: Use UTF-8 encoding when you want readable text as a string. When working with images or other binary data, you may need the Buffer instead.

5. Understanding Error Handling

A file-reading operation can fail for several reasons. For example, the file may not exist, the path may be incorrect, or the application may not have permission to read it.

Therefore, we should check the err parameter before using the file content.

app.js
const fs = require("fs");

fs.readFile("unknown.txt", "utf8", (err, data) => {
    if (err) {
        console.log("Unable to read the file.");
        console.log(err.message);
        return;
    }

    console.log(data);
});

If unknown.txt does not exist, the program displays an error message instead of trying to use missing data.

Example output:

Unable to read the file.
ENOENT: no such file or directory ...

The full error message may vary depending on the operating system and file path.

Important: The return statement stops the current callback from continuing after an error.

6. The fs.readFileSync() Method

The fs.readFileSync() method reads a file synchronously. The program waits until the file has been read before moving to the next statement.

Syntax:

JavaScript
fs.readFileSync(path, encoding);

Example

app.js
const fs = require("fs");

try {
    const data = fs.readFileSync("message.txt", "utf8");

    console.log("File Content:");
    console.log(data);
    console.log("Reading completed.");
} catch (err) {
    console.log("Error reading file:", err.message);
}

Output:

File Content:
Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute
Reading completed.

The synchronous method throws an exception when the operation fails. The try...catch block handles that exception.

Feature fs.readFile() fs.readFileSync()
Operation Asynchronous Synchronous
Result handling Callback Return value
Error handling Check callback error Use try...catch
Execution Does not block while waiting for the file operation Blocks further JavaScript execution until it finishes
Typical use Regular application file operations Small scripts or cases where blocking is acceptable

7. Reading a JSON File

JSON files store structured information in a text format. Node.js can read a JSON file as a string and convert that string into a JavaScript object using JSON.parse().

Step 1: Create student.json

student.json
{
    "id": 101,
    "name": "Rahul",
    "course": "Node.js",
    "city": "Pune"
}

Step 2: Read and Parse the JSON

app.js
const fs = require("fs");

fs.readFile("student.json", "utf8", (err, data) => {
    if (err) {
        console.log("Error reading JSON file:", err.message);
        return;
    }

    try {
        const student = JSON.parse(data);

        console.log("Student ID:", student.id);
        console.log("Student Name:", student.name);
        console.log("Course:", student.course);
        console.log("City:", student.city);
    } catch (parseErr) {
        console.log("Invalid JSON:", parseErr.message);
    }
});

Step 3: Run the Program

Terminal
node app.js

Output:

Student ID: 101
Student Name: Rahul
Course: Node.js
City: Pune

Here, fs.readFile() reads the file, JSON.parse() converts the JSON text into a JavaScript object, and we access individual properties using dot notation.

Note: File-reading errors and invalid JSON syntax are different problems, so the example handles them separately.

8. Common Mistakes While Reading Files

Mistake Solution
Using an incorrect file name Verify the file name and extension.
Placing the file in a different folder Check the file path relative to the current working directory.
Not checking the error parameter Check err before using data.
Forgetting text encoding Specify "utf8" when a text string is required.
Parsing invalid JSON Use valid JSON syntax and handle parsing errors.
Using synchronous reading for large operations in a server Prefer asynchronous reading when blocking execution is undesirable.

9. Practice Tasks

Task 1: Read Employee Details

  1. Create a file named employee.txt.
  2. Store an employee name, ID, department, and salary in it.
  3. Read the file using fs.readFile().
  4. Display all the content in the terminal.
  5. Handle the error if the file does not exist.

Expected result: The employee information should appear in the terminal.

Task 2: Read Product JSON

  1. Create a file named product.json.
  2. Store product ID, product name, and price as JSON properties.
  3. Read the file using fs.readFile().
  4. Convert the file content using JSON.parse().
  5. Display each property separately.

Expected result: Product details should appear as individual values in the terminal.

Summary

Reading files in Node.js allows an application to retrieve information stored in files. The fs.readFile() method reads files asynchronously and provides the result through a callback. Specifying "utf8" returns readable text instead of a Buffer. Error handling is important because files may be missing, inaccessible, or invalid.

The fs.readFileSync() method reads files synchronously and can be used with try...catch to handle errors. We also learned how to read a JSON file and convert its content into a JavaScript object using JSON.parse(). These techniques are useful for reading configuration, student records, and other file-based information in Node.js applications at CIIT Training Institute.