How do I delete a file with node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
I don\'t see a remove command?
fs-extra
provides a remove method:
const fs = require('fs-extra')
fs.remove('/tmp/myfile')
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})
https://github.com/jprichardson/node-fs-extra/blob/master/docs/remove.md
Remove files from the directory that matched regexp for filename. Used only fs.unlink - to remove file, fs.readdir - to get all files from a directory
var fs = require('fs');
const path = '/path_to_files/filename.anyextension';
const removeFile = (fileName) => {
fs.unlink(`${path}${fileName}`, function(error) {
if (error) {
throw error;
}
console.log('Deleted filename', fileName);
})
}
const reg = /^[a-zA-Z]+_[0-9]+(\s[2-4])+\./
fs.readdir(path, function(err, items) {
for (var i=0; i<items.length; i++) {
console.log(items[i], ' ', reg.test(items[i]))
if (reg.test(items[i])) {
console.log(items[i])
removeFile(items[i])
}
}
});
Here below my code which works fine.
const fs = require('fs');
fs.unlink(__dirname+ '/test.txt', function (err) {
if (err) {
console.error(err);
}
console.log('File has been Deleted');
});
Here the code where you can delete file/image from folder.
var fs = require('fs');
Gallery.findById({ _id: req.params.id},function(err,data){
if (err) throw err;
fs.unlink('public/gallery/'+data.image_name);
});
you can use del module to remove one or more files in the current directory. what's nice about it is that protects you against deleting the current working directory and above.
const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
console.log('Deleted files and folders:\n', paths.join('\n'));
});