Last updated: Mar 7, 2024
Reading timeยท5 min
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.
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.
my_project/ index.js animal.png
You can delete the animal.png
file with the following code sample.
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); }
If you use the older require()
syntax, replace the import fs from 'fs'
line
with the following line.
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
.
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.
const path = './animal.png';
If you have to go one directory up, use the '../'
prefix.
For example, assuming you have the following folder structure.
Desktop/ my_project/ index.js animal.png
We have to go one directory up to delete the animal.png
file from 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.
The most common causes of an error are:
catch
block runs because the file isn't found.You can use the fs.unlink() method to delete a file asynchronously.
The method takes the following 2 parameters:
Name | Description |
---|---|
path | The path to the file that is to be deleted. |
callback | A 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.
my_project/ index.js animal.png
You can delete the animal.png
file asynchronously with the following code
sample.
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}`); } });
If you use the older require()
syntax, replace the import statement with the
following line.
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.
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.
animal.png
file, so trying to pass it to unlink
again would raise an error as the file no longer exists.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);
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.
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.
my_project/ index.js animal.png
You can delete the animal.png
file with the following code sample.
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);
If you use the older require()
syntax, replace the import fs from 'fs'
line
with the following line.
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.
The error gets handled by the catch()
block and its message gets logged to the
console.
You can learn more about the related topics by checking out the following tutorials: