How to Delete a File in Node JS

The following tutorial will describe how to delete files that you no longer need, deleting files using node js extremely simple with node js’s fs library.

Note: There is no way of undoing deleted files, just keep that in mind.

To delete files, simply pass a file path as parameter to fs.unlink(path, callback), for sync version call unlinkSync(path). Note that unlink deals only with files, to delete directories you need iterate over directories and files, will show you deleting directories and it’s files also here. it’s too easy, isn’t it?

How to use unlink() to Delete a file

Now to delete testFile.txt, we simply run a node js script which is located in the same directory where file is located. Unlink method just needs to know the name of the file, if file is in another location pass the path of the file, by default it will search for file in the script location(current directory of the script file).

asynchronous – delete example

synchronous – delete example

Delete files of directory

So our first task is to iterate over directories and sub directories to find the files, after finding file just apply unlink() method, lets do it…

Delete array of files

Just iterate over the array of files and apply unlink() method on each file as shown below.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments Protection Status
Would love your thoughts, please comment.x