How to Delete Files in Node.js Safely: Step-by-Step Guide

Robin
Updated on March 5, 2023

Node.js provides a built-in module called fs (short for file system) that allows you to interact with the file system in a variety of ways, including deleting files.

To delete a file in Node.js use the unlink() method from the fs module. It accepts a path of a file. It works asynchronously with a callback or there is another version that returns a promise. For deleting synchronously, we can use the unlinkSync() method.

In this step-by-step guide, we'll explore the different methods for deleting files in Node.js, from synchronous to asynchronous with callback and promises.

By following these guidelines, you can safely delete files in your Node.js applications and avoid potential risks.

Check If the File Exists Before Deleting

Before attempting to delete a file, you should first check whether the file actually exists. This is important to avoid accidentally deleting the wrong file or causing errors in your code. You can use the fs.existsSync() method to check if a file exists.

          const fs = require('fs');

const filePath = './images/banner.jpg';

if (fs.existsSync(filePath)) {
  // The file exists, so you can proceed with deleting it
} else {
  console.log('File not found');
}
        

If the file doesn't exist in that path, the else block will run. But if that file exists, the if block will execute. You can write your code for deleting the file inside this block. Because when you try to delete a file that doesn't present, it will throw an error.

Also Read: How to Check If a File Exists in Node.js (Best Methods)

How to Delete a File Synchronously in NodeJS

To delete a file synchronously in NodeJS, you can use the fs.unlinkSync() method. you need to import the built-in fs module To access the file system APIs in NodeJS.

Once you've imported the fs module, you can use the fs.unlinkSync() method to delete the file at the specified path.

          const fs = require('fs')

const filePath = './images/banner1.jpg'

if (fs.existsSync(filePath)) {
    // The file exists, so you can proceed with deleting it
    try {
        fs.unlinkSync(filePath)
        console.log('File deleted successfully')
    } catch (err) {
        console.error(err)
    }
} else {
    console.log('File not found')
}
        

The fs.unlinkSync() method can throw an error if there's a problem with the file system. To handle errors that may occur during the file deletion process, you can wrap the method call in a try...catch block.

In this example, if an error occurs during the file deletion process, it will be caught by the catch block and logged into the console. If the file is successfully deleted, a success message will be logged to the console. You can do anything else after deleting your file.

The problem with this fs.unlinkSync() method for file deletion is that it can block the Node.js event loop, which can lead to performance issues and slower response times.

That's why it is better to use an asynchronous method like fs.unlink() with a callback or promise.

Also Read: Synchronous VS Asynchronous Programming with Examples

Deleting a File Asynchronously with Callback

One way to delete a file asynchronously in Node.js is to use the fs.unlink() method with a callback function. It is the asynchronous version of the fs.unlinkSync() method.

This unlink() method is available in the Node.js fs module. This method takes two arguments - the path to the file to be deleted, and a callback function that is called after the file has been deleted or an error has occurred.

          const fs = require('fs')

const filePath = './images/banner.jpg'

if (fs.existsSync(filePath)) {
    // The file exists, so you can proceed with deleting it
    fs.unlink(filePath, (err) => {
        if (err) {
            console.error(err)
            return
        }

        console.log('File deleted successfully')
    })
} else {
    console.log('File not found')
}
        

In this example, I am calling fs.unlink() method with the path that I want to delete and a callback function.

The callback function has one err argument which is the error object if an error occurs during the deletion process. If no error occurs, the callback function will log a success message to the console.

This asynchronous method will not block the main thread in JavaScript. But if you use it with a callback function, you might face a problem especially when you nest multiple asynchronous operations.

It can lead to callback hell. Your code will become very difficult to read and maintain.

To avoid these issues, you can use unlink() method with promises and async/await syntax to handle asynchronous file deletion in a more readable and error-resistant way.

Also Read: Node.js Cluster: Improve Server Performance with Clustering

Deleting a File Asynchronously with Promises

Promises provide a more readable and error-resistant way to handle asynchronous operations in JavaScript. In the context of file deletion in Node.js, promises can help simplify your code and make it easier to maintain.

You have to import the unlink() method from Nodejs. But in this case, we need to import this method from fs/promises because we want to use the promised version.

          const fs = require('fs')
const { unlink } = require('fs/promises')

const filePath = './images/banner.jpg'

const deleteFile = async (path) => {
    if (fs.existsSync(path)) {
        // The file exists, so you can proceed with deleting it
        try {
            await unlink(path)
            console.log('File deleted successfully')
        } catch (err) {
            console.error(err)
        }
    } else {
        console.log('File not found')
    }
}

deleteFile(filePath)
        

I have an async function called deleteFile() that takes the file path as its parameter. To delete a file asynchronously with async/await, you can use the unlink() method inside this async function, and use the await keyword to wait for the promise to resolve or reject.

If the promise resolves successfully inside the try block, you will see the success message in your console. If the promise rejects with an error, the code inside the catch block will execute and you can handle this error here.

Also Read: Learn How to Get File Extensions in Node.js From Any Files

How to Delete Multiple Files in Node.js

To delete multiple files in Node.js, we can use the unlink() method with promise and async/await syntax. The Promise.all() method can be used to execute multiple promises in parallel. Call unlink() method for each file path and pass them to Promise.all() as an array.

You'll need to define an array of file paths for the files you want to delete. I have a filePaths array with all the file paths that I want to delete.

          const { unlink } = require('fs/promises')

const filePaths = [
    './images/banner.jpg',
    './images/featured.jpg',
    './images/thumbnail.jpg',
]

const deleteFiles = async (paths) => {
    try {
        const promises = paths.map((file) => unlink(file))
        await Promise.all(promises)

        console.log('All files deleted successfully')
    } catch (err) {
        console.error(err)
    }
}

deleteFiles(filePaths)
        

The Promise.all() method takes an array of promises and returns a single promise that resolves when all of the promises in the array have resolved, or rejects when any of the promises in the array reject.

I have a deleteFiles() function that takes an array of file paths as its parameter. Inside this function, I am looping over this array using map() method that returns an array of promises by calling the fs.unlink() method on each file path.

Finally, I am passing this array of promises to the Promise.all() method to resolve or reject.

If all of the promises resolve successfully, the code inside the try block will execute and you will see a success message in your console. If any of the promises reject with an error, the code inside the catch block will execute and you can handle the error here.

The main advantage of this syntax is that it allows you to delete multiple files in parallel, making the process faster and more efficient. It also makes the code easier to read and understand.

Also Read: How to Rename Multiple Files in a Folder Using Node.js (fs Module)

Conclusion

You have seen several ways to delete a file in Node.js, including a synchronous method, and an asynchronous method with callbacks and promises. You can also delete multiple files at once.

There is no need to use any external packages. NodeJS Provides the unlink() method in its fs module that can delete any file. This method supports both callback and promise.

For deleting multiple files, call the unlink() method for each file path and pass them to the Promise.all() as an array. It becomes very easy to understand and maintainable when we do it with async/await syntax.

Now, you can choose any of those methods to delete files in Node.js depending on the specific use case and requirements of the application.

Related Posts