What is the best way to delete several files in node.js?
function deleteFiles(files, callback){
...
}
var files = [\'file1.js\', \'file2.jpg\', \'file3.css\
You can use this to delete multiple files (for linux env ES6 syntax)
import {execSync} from "child_process";
...
...
const files = ['file1.js', 'file2.jpg', 'file3.css'];
// just example path
const rootDir = '/var/www/files/';
if (files.length > 0)
execSync('rm -f' + files.map(o => rootDir + o.replace(/(\s+)/g, '\\$1')).join(' '));
rm -f to ignore if files are missing and replace to escape spaces if file names contains it,
Best way is delete files synchronously into a loop using unlinkSync(path)
function (see the doc), from node v7.6.0
so far.
Syntax is provided below:
// myListOfFiles will be your list of files with paths relative to your script.
myListOfFiles.forEach(filePath => {
fs.unlinkSync(filePath);
return;
});
A reference here
I personally like shortcode (in one line)
files.forEach(path => fs.existsSync(path) && fs.unlinkSync(path))
So maybe using async/await style it's easier (complete example):
try {
var files = ['file1.js', 'file2.jpg', 'file3.css'];
files.forEach(path => fs.existsSync(path) && fs.unlinkSync(path))
// success code here
} catch (err) {
// error handling here
console.error(err)
}
Promisified and slightly improved version Chris answer.
async deleteAll(filePathsList) {
try {
await this.deleteFiles(filePathsList);
logger.log('info', "Following files deleted successfully from EFS --> " + filePathsList.toString());
return true;
} catch (error) {
logger.log('error', error.stack || error);
logger.log('error', "Error occured while deleting files from EFS");
return false;
}
}
async deleteFiles(files) {
return new Promise((resolve, reject) => {
let i = files.length;
files.forEach(function(filepath) {
fs.unlink(filepath, function(err) {
i--;
if (err && err.code == 'ENOENT') {
// file doens't exist
logger.log('info', "Following file doesn't exist, So won't be deleted-->" + (filepath || ''));
} else if (err) {
// other errors, e.g. maybe we don't have enough permission
logger.log('error', "Error occured while deleting the file " + (filepath || '') + " due to error" + err);
reject(err);
return;
} else if (i <= 0) {
resolve();
}
});
});
})
}
This deletes the files in an array and runs the callback once only after all files have been deleted.
function deleteFiles(files, callback){
if (files.length==0) callback();
else {
var f = files.pop();
fs.unlink(f, function(err){
if (err) callback(err);
else {
console.log(f + ' deleted.');
deleteFiles(files, callback);
}
});
}
}
Here is a code to delete several files from directory in node.js,
var fs = require('fs');
var removeFile= function (err) {
if (err) {
console.log("unlink failed", err);
} else {
console.log("file deleted");
}
}
fs.unlink('filepath', removeFile); // for single file
//for multiple files...
_.map(yourArray,(files)=>{
fs.unlink('filepath', removeFile);
});