How to delete a File in Node.js and JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
5 min

banner

# Table of Contents

  1. Deleting a file using fs.unlinkSync()
  2. Deleting a file asynchronously using fs.unlink()
  3. Deleting a file using unlink() with fs.promises and async/await

# How to delete a File in Node.js and JavaScript

You have no access to the user's file system when in a browser environment. Deleting a file from the user's file system when they visit your website is not possible.

However, you can use Node.js to delete files from your server's file system.

Use the fs.unlink() and fs.unlinkSync() methods to delete a file in Node.js.

The fs.unlink() method asynchronously deletes a file whereas the fs.unlinkSync() method deletes a file synchronously.

# Deleting a file using fs.unlinkSync() in Node.js

Let's look at an example of using the fs.unlinkSync() method to delete a file in Node.js.

The following code sample assumes that you have an index.js script and an animal.png file that you want to delete.

shell
my_project/ index.js animal.png

You can delete the animal.png file with the following code sample.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use require() syntax uncomment this // const fs = require('fs') const path = './animal.png'; try { fs.unlinkSync(path); console.log(`Deleted the file under ${path}`); } catch (err) { console.log('An error occurred: ', err.message); }

delete file using unlinksync

The code for this article is available on GitHub

If you use the older require() syntax, replace the import fs from 'fs' line with the following line.

index.js
const fs = require('fs')

The unlinkSync() method takes a single parameter - the path that points to the file.

You can add the code sample to a file called index.js and run the file with node index.js.

shell
node index.js

Make sure to specify the correct path to the file.

The path in the example assumes that there is an animal.png file located in the same directory as your index.js file.

index.js
const path = './animal.png';

If you have to go one directory up, use the '../' prefix.

For example, assuming you have the following folder structure.

shell
Desktop/ my_project/ index.js animal.png

We have to go one directory up to delete the animal.png file from index.js.

index.js
const path = '../animal.png';

Similarly, if you need to go two directories up, you would use a prefix of ../../.

If an error occurs, it gets passed to the catch function.

handle error in catch

The most common causes of an error are:

  1. Specifying an incorrect path to the file.
  2. Already having deleted the file. If the file is already deleted, the catch block runs because the file isn't found.

# Deleting a file asynchronously using fs.unlink() in Node.js

You can use the fs.unlink() method to delete a file asynchronously.

The method takes the following 2 parameters:

NameDescription
pathThe path to the file that is to be deleted.
callbackA function that gets after the operation. If the operation fails, the function gets called with an error.

The following code sample assumes that you have an index.js script and an animal.png file that you want to delete.

shell
my_project/ index.js animal.png

You can delete the animal.png file asynchronously with the following code sample.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use require() syntax uncomment this // const fs = require('fs') const path = './animal.png'; fs.unlinkSync(path, err => { if (err) { console.log(`An error occurred ${err.message}`); } else { console.log(`Deleted the file under ${path}`); } });

delete file using unlink

The code for this article is available on GitHub

If you use the older require() syntax, replace the import statement with the following line.

index.js
const fs = require('fs')

Make sure to specify the correct path to the file.

The path in the example assumes that there is an animal.png file located in the same directory as your index.js file.

index.js
const path = './animal.png';

If you have to go one directory up, use the '../' prefix.

If an error occurs when trying to delete a file, the callback function gets called with the error.

Otherwise, the err variable is set to null.

Let's look at an example call to the unlink() method where an error is raised.

I have already deleted the animal.png file, so trying to pass it to unlink again would raise an error as the file no longer exists.
index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use require() syntax uncomment this // const fs = require('fs') const path = './animal.png'; fs.unlink(path, err => { if (err) { console.log(`An error occurred ${err.message}`); } else { console.log(`Deleted the file under ${path}`); } }); console.log('before'); setTimeout(() => { console.log('bobbyhadz.com'); }, 1000);

unlink handle error

The code for this article is available on GitHub

Notice that the console.log('before') line runs after the fs.unlink() call.

This is because fs.unlink() is an asynchronous method.

The callback function we passed to fs.unlink() gets called with an error and we log the error message.

The setTimeout() function prints a message after a delay of 1 second.

# Deleting a file using unlink() with fs.promises and async/await

An alternative to using the callback syntax is to delete a file using Promises.

You can use the fsPromises.unlink() method to delete a file using the newer async/await or Promise.then() syntax.

The following code sample assumes that you have an index.js script and an animal.png file that you want to delete.

shell
my_project/ index.js animal.png

You can delete the animal.png file with the following code sample.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use require() syntax uncomment this // const fs = require('fs') const fsPromises = fs.promises; async function deleteFile(path) { try { await fsPromises.unlink(path); console.log(`Deleted the file under ${path}`); } catch (err) { console.log('An error occured: ', err.message); } } const path = './animal.png'; deleteFile(path);

delete file using promises

The code for this article is available on GitHub

If you use the older require() syntax, replace the import fs from 'fs' line with the following line.

index.js
const fs = require('fs')

Notice that we used the promises property on the fs module.

The fsPromises.unlink() method takes a path as a parameter and returns a Promise that we can await or call .then() on.

The promise is resolved with no arguments upon success.

If an error is raised, it gets passed to the cath() block.

I already deleted the animal.png file, so if I run the code sample again and error is raised.

handle error promises

The error gets handled by the catch() block and its message gets logged to the console.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev