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
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.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.