我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
我没有看到删除命令?
我如何删除一个文件与node.js?
http://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback
我没有看到删除命令?
当前回答
从filename匹配regexp的目录中删除文件。只使用fs。Unlink -删除文件,fs。Readdir -从目录中获取所有文件
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])
}
}
});
其他回答
我认为你不需要检查文件是否存在,fs。Unlink将为您检查。
fs.unlink('fileToBeRemoved', function(err) {
if(err && err.code == 'ENOENT') {
// file doens't exist
console.info("File doesn't exist, won't remove it.");
} else if (err) {
// other errors, e.g. maybe we don't have enough permission
console.error("Error occurred while trying to remove file");
} else {
console.info(`removed`);
}
});
简单且同步
if (fs.existsSync(pathToFile)) {
fs.unlinkSync(pathToFile)
}
2020的答案
有了节点v14.14.0的发行版,您现在就可以这样做了。
fs.rmSync("path/to/file", {
force: true,
});
https://nodejs.org/api/fs.html#fsrmsyncpath-options
这里的代码,你可以从文件夹中删除文件/图像。
var fs = require('fs');
Gallery.findById({ _id: req.params.id},function(err,data){
if (err) throw err;
fs.unlink('public/gallery/'+data.image_name);
});
如果要在删除前检查文件是否存在。所以,使用fs。Stat或fs。statSync (Synchronous)而不是fs.exists。因为根据最新的node.js文档,fs。现在已弃用。
例如:-
fs.stat('./server/upload/my.csv', function (err, stats) {
console.log(stats);//here we got all information of file in stats variable
if (err) {
return console.error(err);
}
fs.unlink('./server/upload/my.csv',function(err){
if(err) return console.log(err);
console.log('file deleted successfully');
});
});