我如何删除一个文件与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
我没有看到删除命令?
当前回答
我认为你不需要检查文件是否存在,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`);
}
});
其他回答
fs.unlinkSync()如果你想同步删除文件 Fs.unlink()如果你想异步删除它。
在这里你可以找到一篇好文章。
fs很简单。
var fs = require('fs');
try{
var sourceUrls = "/sampleFolder/sampleFile.txt";
fs.unlinkSync(sourceUrls);
}catch(err){
console.log(err);
}
我认为你应该使用fs。unlink。
更多关于fs的信息可以在这里找到。
你可以使用fs。Unlink (path, callback)函数。下面是一个带有"error-back"模式的函数包装器示例:
/ /依赖性。 Const fs = require('fs'); //删除文件 const deleteFile = (filePath, callback) => { //断开文件链接。 fs。unlink(filePath, (error) => { If(!错误){ 回调(假); }其他{ callback('删除文件错误'); } }) };
2020的答案
有了节点v14.14.0的发行版,您现在就可以这样做了。
fs.rmSync("path/to/file", {
force: true,
});
https://nodejs.org/api/fs.html#fsrmsyncpath-options