我如何删除一个文件与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很简单。
var fs = require('fs');
try{
var sourceUrls = "/sampleFolder/sampleFile.txt";
fs.unlinkSync(sourceUrls);
}catch(err){
console.log(err);
}
其他回答
2019年和节点10+已经到来。下面的版本采用了甜异步/等待的方式。
现在不需要对fs进行换行。不再链接到Promises,也不再使用额外的包(比如fs-extra)。
只需使用本地fs承诺API。
const fs = require('fs').promises;
(async () => {
try {
await fs.unlink('~/any/file');
} catch (e) {
// file doesn't exist, no permissions, etc..
// full list of possible errors is here
// http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS
console.log(e);
}
})();
这里是fsPromises。从Node文档中断开规范链接。
另外,请注意fs。在Node 10.x中承诺API标记为实验性。X(但是工作完全正常),并且从11.14.0开始不再是实验性的。
使用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);
});
您可以使用del模块删除当前目录中的一个或多个文件。它的好处是可以保护您不删除当前工作目录和以上目录。
const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
console.log('Deleted files and folders:\n', paths.join('\n'));
});