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

Appending Files in Node.js

Appending files means adding new content to the end of an existing file without removing its previous content. Node.js provides the fs.appendFile() method to perform this operation.

For example, a student management application may need to add a new student's details to a text file every time a student registers. Appending allows us to add the new details while preserving the existing records.


1. What Does Appending a File Mean?

Appending means adding new data after the existing content of a file. Unlike the default behaviour of fs.writeFile(), appending does not replace the existing content.

Suppose a file named students.txt contains:

students.txt - Before
Rahul
Priya

Now we append a new student named Amit.

Existing File

Rahul, Priya

↓
fs.appendFile()

Adds Amit at the end

↓
Updated File

Rahul, Priya, Amit

The file now contains:

students.txt - After
Rahul
Priya
Amit

2. The fs.appendFile() Method

The fs.appendFile() method adds data to the end of a file asynchronously. If the specified file does not exist, Node.js normally creates it.

Syntax:

JavaScript
fs.appendFile(path, data, callback);

Parameters:

Parameter Meaning
path The path of the file to which data will be added.
data The string or supported data to append.
callback A function called when the operation completes or fails.

The callback uses the error-first pattern: (err). If the operation fails, the error parameter contains information about the failure.

3. First Example: Append Text to a File

Let's create a file named message.txt and add additional content to it.

Step 1: Create a Project Folder

Terminal
mkdir AppendingFilesDemo
cd AppendingFilesDemo
npm init -y

Step 2: Create message.txt

Create a file named message.txt with this content:

message.txt - Before
Welcome to Node.js!

Step 3: Create app.js

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

fs.appendFile(
    "message.txt",
    "\nWe are learning file handling.",
    (err) => {
        if (err) {
            console.log("Error appending file:", err.message);
            return;
        }

        console.log("Content appended successfully!");
    }
);

Step 4: Run the Program

Terminal
node app.js

Terminal output:

Content appended successfully!

Updated content of message.txt:

message.txt - After
Welcome to Node.js!
We are learning file handling.

Explanation:

  • require("fs") imports the File System module.
  • "message.txt" specifies the destination file.
  • "\nWe are learning file handling." adds a new line followed by the new text.
  • fs.appendFile() adds the content at the end.
  • The callback checks for errors and displays a success message.

4. Append Multiple Lines

We can append multiple lines to a file using the newline character \n.

Suppose students.txt already contains:

students.txt - Before
Rahul
Priya

Now append two more student names.

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

const newStudents = "\nAmit\nSneha";

fs.appendFile("students.txt", newStudents, "utf8", (err) => {
    if (err) {
        console.log("Error:", err.message);
        return;
    }

    console.log("New students added successfully!");
});

Output:

New students added successfully!

Updated students.txt:

students.txt - After
Rahul
Priya
Amit
Sneha

The new names are added after the existing names. The original records remain unchanged.

Important: The newline character at the beginning of newStudents separates the new records from the existing content. If the file already ends with a newline, this may create an extra blank line.

5. Append Student Details

Let's build a practical example that adds student details to a file whenever the program runs.

Step 1: Create app.js

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

const studentName = "Rahul";
const course = "Node.js";

const studentRecord =
    `Student Name: ${studentName}, Course: ${course}\n`;

fs.appendFile("studentRecords.txt", studentRecord, "utf8", (err) => {
    if (err) {
        console.log("Error saving student:", err.message);
        return;
    }

    console.log("Student record saved successfully!");
});

Step 2: Run the Program

Terminal
node app.js

Output:

Student record saved successfully!

Content of studentRecords.txt after the first run:

studentRecords.txt
Student Name: Rahul, Course: Node.js

If you run the same program again, another record will be added at the end of the file.

Content after the second run:

studentRecords.txt
Student Name: Rahul, Course: Node.js
Student Name: Rahul, Course: Node.js
Note: This example adds the same record every time it runs. A real application should validate records and prevent unwanted duplicate entries when required.

6. The fs.appendFileSync() Method

The fs.appendFileSync() method appends content synchronously. It waits for the append operation to finish before the program continues.

Syntax:

JavaScript
fs.appendFileSync(path, data);

Example

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

try {
    fs.appendFileSync(
        "course.txt",
        "\nTopic: File System Module"
    );

    console.log("Course information appended successfully!");
} catch (err) {
    console.log("Error appending file:", err.message);
}

Output:

Course information appended successfully!

If course.txt previously contained Course: Node.js, the resulting file will contain:

course.txt
Course: Node.js
Topic: File System Module

Unlike the asynchronous method, the synchronous method throws an exception when the operation fails. We can handle it with try...catch.

Feature fs.appendFile() fs.appendFileSync()
Operation Asynchronous Synchronous
Completion Handled through a callback Returns after the operation completes
Error handling Check the callback error Use try...catch
Blocking Does not block while waiting for the file operation Blocks further JavaScript execution until it finishes

7. Difference Between Writing and Appending

The main difference is how each method handles the content already present in a file.

Feature fs.writeFile() fs.appendFile()
Purpose Writes or replaces file content Adds content at the end
Existing content Replaced by default Preserved
Creates missing file Yes, normally Yes, normally
Asynchronous method fs.writeFile() fs.appendFile()
Synchronous method fs.writeFileSync() fs.appendFileSync()

Quick Example

Original content:

Rahul

Using writeFile():

Priya

Rahul is replaced by Priya.

Using appendFile():

Rahul
Priya

Rahul remains, and Priya is added at the end.

8. Error Handling While Appending Files

File operations can fail because of invalid paths, insufficient permissions, or other file-system problems. We should check errors before displaying a success message.

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

fs.appendFile("logs/activity.txt", "Application started\n", (err) => {
    if (err) {
        console.log("Unable to append log:", err.message);
        return;
    }

    console.log("Log entry added successfully!");
});

In this example, the logs directory must already exist. If it does not exist, the append operation will normally fail because Node.js does not automatically create missing parent directories.

If the directory is missing, create it first or use fs.mkdir() with the appropriate options.

Remember: appendFile() can create a missing file, but it does not automatically create missing parent directories.

9. Common Mistakes While Appending Files

Mistake Solution
Forgetting the newline character Use \n when records should appear on separate lines.
Using an incorrect file path Verify the file path and current working directory.
Assuming missing directories are created automatically Create the parent directory before appending.
Not handling errors Check the callback error or use try...catch for synchronous operations.
Appending duplicate records unintentionally Validate records before adding them.
Using appendFile() when content must be replaced Use fs.writeFile() when replacing content is intended.

10. Practice Tasks

Task 1: Append Employee Details

  1. Create a file named employees.txt.
  2. Add one employee name manually.
  3. Write a Node.js program using fs.appendFile().
  4. Append another employee name on a new line.
  5. Display a success message after the operation completes.
  6. Run the program again and observe the file content.

Expected result: The original employee name should remain, and the new name should be added at the end of the file.

Task 2: Create an Activity Log

  1. Create a project named ActivityLogApp.
  2. Create a file named activity.txt.
  3. Append the message Application started.
  4. Append another message, User logged in.
  5. Place each message on a separate line.
  6. Handle errors and verify the saved content.

Expected result: Both activity messages should be present in the file, in the order they were successfully appended.

Summary

Appending files in Node.js means adding new information to the end of an existing file without replacing its previous content. The fs.appendFile() method performs this operation asynchronously, while fs.appendFileSync() performs it synchronously. Both methods can create a missing file, but missing parent directories must be created separately.

In this lesson, we learned how to append text, add multiple lines, save student records, handle file errors, and compare appending with writing. These techniques are useful for maintaining text records and activity logs in Node.js applications at CIIT Training Institute.