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

Deleting Files in Node.js

Deleting files is an important file-handling operation in Node.js. The File System module provides methods to remove files from the file system using JavaScript code.

For example, an application may need to remove temporary files, outdated reports, or unnecessary text files. Node.js provides fs.unlink() and fs.unlinkSync() to delete files.


1. What Does Deleting a File Mean?

Deleting a file means removing a file from its location in the file system. Once a file has been deleted successfully, it cannot normally be accessed through its previous path.

Suppose an application creates a temporary file named temp.txt. After completing its work, the application may delete that file because it is no longer needed.

File Exists

temp.txt

↓
Node.js fs Module

fs.unlink()

↓
File Deleted

temp.txt no longer exists at that path

2. The fs.unlink() Method

The fs.unlink() method deletes a file asynchronously. It allows other JavaScript work to continue while the file operation is being handled.

Syntax:

JavaScript
fs.unlink(path, callback);

Parameters:

Parameter Meaning
path The path of the file to delete.
callback A function called when the deletion operation completes or fails.

The callback follows the error-first pattern: (err). If deletion succeeds, the error is null. If the operation fails, the error parameter contains information about the failure.

Important: fs.unlink() is used to delete files, not to remove directories. We will learn directory operations in the next lesson.

3. First Example: Delete a Text File

Let's create a file named temp.txt and delete it using Node.js.

Step 1: Create a Project Folder

Terminal
mkdir DeletingFilesDemo
cd DeletingFilesDemo
npm init -y

Step 2: Create temp.txt

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

temp.txt
This is a temporary file.
It is no longer required.

Step 3: Create app.js

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

fs.unlink("temp.txt", (err) => {
    if (err) {
        console.log("Error deleting file:", err.message);
        return;
    }

    console.log("File deleted successfully!");
});

Step 4: Run the Program

Terminal
node app.js

Output:

File deleted successfully!

After successful execution, temp.txt is removed from the project folder.

Before execution:

DeletingFilesDemo/

app.js

temp.txt

After successful deletion:

DeletingFilesDemo/

app.js

Explanation:

  • require("fs") imports the File System module.
  • "temp.txt" specifies the file to delete.
  • fs.unlink() starts the asynchronous deletion operation.
  • if (err) checks whether the operation failed.
  • The success message is displayed only after successful deletion.

4. Handling Errors While Deleting Files

File deletion can fail if the file does not exist, the path is incorrect, or the application does not have sufficient permissions.

Therefore, we should always check the error parameter before displaying a success message.

Example: Delete a Missing File

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

fs.unlink("unknown.txt", (err) => {
    if (err) {
        console.log("Unable to delete file.");
        console.log(err.message);
        return;
    }

    console.log("File deleted successfully!");
});

If unknown.txt does not exist, the deletion operation fails.

Example output:

Unable to delete file.
ENOENT: no such file or directory ...

The complete error message depends on the operating system and the file path.

Remember: The return statement prevents the callback from continuing to the success message after an error.

5. The fs.unlinkSync() Method

The fs.unlinkSync() method deletes a file synchronously. The program waits for the deletion operation to complete before continuing.

Syntax:

JavaScript
fs.unlinkSync(path);

Example

First, make sure that a file named oldFile.txt exists in the current project directory.

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

try {
    fs.unlinkSync("oldFile.txt");

    console.log("File deleted successfully!");
} catch (err) {
    console.log("Error deleting file:", err.message);
}

Output when the file exists:

File deleted successfully!

If the file does not exist, the method throws an exception. The catch block handles that exception and displays an error message.

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

Asynchronous methods are generally preferred for regular file operations in server applications when blocking execution is undesirable.

6. Delete a File After Checking Whether It Exists

Sometimes, an application needs to check whether a file exists before deleting it. One option is to use fs.access() before calling fs.unlink().

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

fs.access("temp.txt", fs.constants.F_OK, (accessErr) => {
    if (accessErr) {
        console.log("File does not exist.");
        return;
    }

    fs.unlink("temp.txt", (deleteErr) => {
        if (deleteErr) {
            console.log("Error deleting file:", deleteErr.message);
            return;
        }

        console.log("File deleted successfully!");
    });
});

Possible output when the file exists:

File deleted successfully!

Possible output when the file is missing:

File does not exist.

The example checks the file first and then attempts deletion. However, the file could change between these two operations. For many applications, calling fs.unlink() directly and handling its error is simpler and more reliable.

7. Delete Multiple Files

If an application needs to delete several files, we can use fs.unlink() for each file and wait for all operations to finish.

In this example, make sure all three files exist in the project directory before running the program.

app.js
const fs = require("fs");
const { promisify } = require("util");

const unlinkAsync = promisify(fs.unlink);

async function deleteFiles() {
    const files = [
        "temp1.txt",
        "temp2.txt",
        "temp3.txt"
    ];

    for (const file of files) {
        try {
            await unlinkAsync(file);
            console.log(`${file} deleted successfully.`);
        } catch (err) {
            console.log(`Could not delete ${file}: ${err.message}`);
        }
    }
}

deleteFiles();

Example output when all files exist:

temp1.txt deleted successfully.
temp2.txt deleted successfully.
temp3.txt deleted successfully.

The loop processes the files one at a time. If a file cannot be deleted, its error is displayed and the loop continues with the next file.

Important: Only delete files that your application is allowed to remove. Verify file paths carefully before running deletion code.

8. Difference Between Deleting Files and Directories

Files and directories are different types of file-system resources. The method used to delete a file is not the same as every method used to remove a directory.

Operation Method Purpose
Delete a file fs.unlink() Removes a file.
Delete a file synchronously fs.unlinkSync() Removes a file synchronously.
Create a directory fs.mkdir() Creates a directory.
Read directory contents fs.readdir() Lists directory entries.
Remove a directory fs.rmdir() or fs.rm(), as appropriate Removes a directory, subject to the method's rules and options.

We will explore directory operations in the next lesson.

9. Common Mistakes While Deleting Files

Mistake Solution
Using the wrong file name Verify the file name and extension.
Using an incorrect path Check the path relative to the current working directory.
Not handling deletion errors Check the callback error or use try...catch.
Using unlink() to remove a directory Use the appropriate directory-removal method.
Displaying success before deletion completes Display the success message inside the callback after successful deletion.
Deleting important files accidentally Verify the path and confirm the file is safe to delete.

10. Practice Tasks

Task 1: Delete a Temporary File

  1. Create a project folder named TempFileApp.
  2. Initialize the project using npm init -y.
  3. Create a file named temp.txt.
  4. Write a Node.js program using fs.unlink().
  5. Handle errors if the file does not exist.
  6. Display a success message after deletion.

Expected result: The file should be removed successfully, and a confirmation message should appear in the terminal.

Task 2: Delete Old Report Files

  1. Create three test files named report1.txt, report2.txt, and report3.txt.
  2. Create an array containing these file names.
  3. Delete each file using an asynchronous method.
  4. Handle each file's error separately.
  5. Display a message for every successful deletion.

Expected result: Each existing test file should be deleted, and the terminal should show the corresponding result.

Summary

Deleting files in Node.js allows applications to remove unnecessary files from the file system. The fs.unlink() method deletes a file asynchronously, while fs.unlinkSync() deletes it synchronously. Both methods can fail when a file does not exist or the application lacks the required permissions.

In this lesson, we learned how to delete one file, handle errors, check file existence, and process multiple files. We also understood the difference between deleting files and removing directories. These techniques help developers manage temporary files and other application resources safely in Node.js projects at CIIT Training Institute.