Deleting Files

Introduction

Deleting files is a common operation in backend development. Applications often remove temporary files, old log files, outdated reports, uploaded documents, cache files, and unnecessary data to free up storage and keep the file system organized.

Node.js provides built-in methods through its File System (fs) module to delete files safely without requiring any external libraries.

For automation engineers, file deletion is frequently used to remove old test reports, clean up screenshots, delete temporary files, clear logs, and prepare the test environment before or after automation execution.


What is File Deletion?

File deletion is the process of permanently removing a file from the file system.

Node.js provides methods to:

  • Delete files asynchronously

  • Delete files synchronously

  • Remove temporary files

  • Clean up generated reports

  • Delete log files


Why Delete Files?

Deleting files allows applications to:

  • Remove temporary files

  • Delete old reports

  • Clean up log files

  • Free storage space

  • Remove outdated data

  • Maintain a clean project structure

  • Prepare the environment for new executions


The File System (fs) Module

Node.js uses the built-in fs (File System) module for file operations.

Import it before deleting files.

const fs = require("fs");

Asynchronous File Deletion

The most commonly used method is fs.unlink().

Syntax

fs.unlink(path, callback);

Parameters

ParameterDescription
pathFile path
callbackFunction executed after deletion completes

Example 1: Delete a File

Suppose sample.txt exists.

const fs = require("fs");

fs.unlink(
    "sample.txt",
    (error) => {
        if (error) {
            console.log(error);
            return;
        }

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

Sample Output

File deleted successfully.

Example 2: Handle File Not Found

const fs = require("fs");

fs.unlink(
    "missing.txt",
    (error) => {
        if (error) {
            console.log("File does not exist.");
            return;
        }

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

Sample Output

File does not exist.

Synchronous File Deletion

Node.js also provides fs.unlinkSync().

This method blocks execution until the file has been deleted.

Syntax

fs.unlinkSync(path);

Example 3: Delete a File Synchronously

const fs = require("fs");

fs.unlinkSync("sample.txt");

console.log("File deleted.");

Sample Output

File deleted.

Asynchronous vs Synchronous Deletion

Featureunlink()unlinkSync()
BlockingNoYes
PerformanceBetter for large applicationsSlower because execution waits
Uses CallbackYesNo
RecommendedYesOnly when necessary

Deleting Multiple Files

const fs = require("fs");

const files = [
    "report1.txt",
    "report2.txt",
    "report3.txt"
];

files.forEach(file => {
    fs.unlink(file, (error) => {
        if (error) {
            console.log(file + " not found.");
            return;
        }

        console.log(file + " deleted.");
    });
});

Sample Output

report1.txt deleted.
report2.txt deleted.
report3.txt deleted.

Real-World Example

Delete an old report before generating a new one.

const fs = require("fs");

fs.unlink(
    "report.html",
    (error) => {
        if (error) {
            console.log("Previous report not found.");
            return;
        }

        console.log("Old report removed.");
    }
);

Sample Output

Old report removed.

Automation Testing Example

Deleting files is commonly used in automation frameworks.

Playwright Example

Delete an old screenshot.

const fs = require("fs");

fs.unlinkSync("homepage.png");

Selenium Example

Delete an old execution log.

const fs = require("fs");

fs.unlinkSync("execution.log");

Cypress Example

Remove an old API response file.

const fs = require("fs");

fs.unlinkSync("response.json");

API Testing Example

Delete an old request payload.

const fs = require("fs");

fs.unlinkSync("payload.json");

Data-Driven Testing Example

Delete an old employee data file.

const fs = require("fs");

fs.unlinkSync("employees.json");

Common Mistakes

Forgetting to Import fs

Incorrect:

unlink("sample.txt");

Correct:

const fs = require("fs");

Deleting a File Without Checking if It Exists

Attempting to delete a file that does not exist results in an error.

A common approach is to handle the error inside the callback or use fs.existsSync() before deleting.

const fs = require("fs");

if (fs.existsSync("sample.txt")) {
    fs.unlinkSync("sample.txt");
}

Accidentally Deleting Important Files

File deletion is permanent.

Always verify the file path before calling unlink() or unlinkSync().


Best Practices

  • Prefer fs.unlink() for most applications because it is asynchronous.

  • Use fs.unlinkSync() only when blocking behavior is acceptable.

  • Check whether a file exists before deleting it when appropriate.

  • Handle deletion errors properly.

  • Delete only files that are no longer required.

  • Keep backup copies of important files if necessary.

  • Use dedicated folders for temporary files and reports.


Conclusion

Deleting files is an important part of file management in Node.js. The built-in fs module provides simple methods for removing unnecessary files, cleaning up temporary data, and maintaining an organized file system.

For automation engineers, deleting files is essential for cleaning old reports, removing screenshots, clearing logs, and preparing the environment for fresh test executions.

Mastering file deletion helps you build efficient Node.js applications and reliable automation frameworks.


Frequently Asked Questions (FAQs)

Which module is used to delete files in Node.js?

The built-in fs (File System) module.


How do I import the fs module?

const fs = require("fs");

Which method deletes files asynchronously?

Use:

fs.unlink(path, callback);

Which method deletes files synchronously?

Use:

fs.unlinkSync(path);

What happens if the file does not exist?

Node.js throws an error, which should be handled appropriately.


Why is deleting files important in automation testing?

Automation engineers delete old reports, screenshots, log files, temporary files, and generated test data to keep the test environment clean and avoid conflicts between test runs.


Key Takeaways

  • Node.js uses the built-in fs module for deleting files.

  • fs.unlink() deletes files asynchronously.

  • fs.unlinkSync() deletes files synchronously.

  • File deletion permanently removes a file from the file system.

  • Handle deletion errors properly.

  • Check file existence when appropriate before deleting.

  • Asynchronous deletion is recommended for most applications.

  • File deletion is widely used in Playwright, Selenium, Cypress, API testing, and Node.js applications.

  • Use file deletion to clean up reports, logs, screenshots, and temporary files.

  • Mastering file deletion is essential for backend development and automation testing.