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
const fs = require('fs'); const filePath = 'testFile.txt'; fs.access(filePath, error => { if (!error) { fs.unlink(filePath,function(error){ console.log(error); }); } else { console.log(error); } });
synchronous – delete example
const fs = require('fs'); const filePath = 'testFile.txt'; fs.access(filePath, error => { if (!error) { fs.unlinkSync(filePath); } else { console.log(error); } });
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…
const fs = require('fs'); const path = require("path") const deleteFolderRecursive = function (directory_path) { if (fs.existsSync(directory_path)) { fs.readdirSync(directory_path).forEach(function (file, index) { var currentPath = path.join(directory_path, file); if (fs.lstatSync(currentPath).isDirectory()) { deleteFolderRecursive(currentPath); } else { fs.unlinkSync(currentPath); // delete file } }); fs.rmdirSync(directory_path); // delete directories } }; // call function by passing directory path deleteFolderRecursive('test');
Delete array of files
Just iterate over the array of files and apply unlink()
method on each file as shown below.
const fs = require('fs'); const files = ['testFile.txt','testFile2.txt']; files.forEach(function(filePath) { fs.access(filePath, error => { if (!error) { fs.unlinkSync(filePath,function(error){ console.log(error); }); } else { console.log(error); } }); });