我如何删除一个文件与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
我没有看到删除命令?
当前回答
rm -rf它
require("fs").rmSync(file_or_directory_path_existing_or_not, {recursive: true, force: true});
// Added in Node.js 14.14.0.
要求(fs)。rmSync或require("fs").rm。
其他回答
2020的答案
有了节点v14.14.0的发行版,您现在就可以这样做了。
fs.rmSync("path/to/file", {
force: true,
});
https://nodejs.org/api/fs.html#fsrmsyncpath-options
使用NPM模块fs-extra,它提供了fs中的所有内容,加上所有内容都是承诺的。另外,还有一个fs.remove()方法可用。
我认为你不需要检查文件是否存在,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`);
}
});
这里的代码,你可以从文件夹中删除文件/图像。
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。断开链接删除文件。
但根据Node.js文档
不建议在调用fs.open()、fs.readFile()或fs.writeFile()之前使用fs.stat()检查文件是否存在。相反,用户代码应该直接打开/读取/写入文件,并在文件不可用时处理引发的错误。 要检查一个文件是否存在而不进行操作,建议使用fs.access()。
检查文件是否可以删除,使用fs。访问相反
fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
console.log(err ? 'no access!' : 'can read/write');
});