如何解决如何在javascript/node.js中删除当前目录下的多个PDF文件
我想删除当前目录下以 .pdf 结尾的多个文件。假设我有 3 个不同的 pdf 文件、1 个图像文件和一个文本文件,那么在这些文件中,我只想删除这 3 个不同的 pdf 文件。
我尝试过的。
第一种方法
fs.unlinkSync('./'+*+pdfname);
-> 我知道这没有意义
第二种方法
try {
var files = (here the list of files should come. However i am failing to get those);
var path="./"
files.forEach(path => fs.existsSync(path) && fs.unlinkSync(path))
} catch (err) {
console.error("not exist")
}
任何不同的方法将不胜感激。
解决方案更新:
我已经找到了满足我需求的解决方案,我只是想让我的函数删除所有 pdf 文件并且函数是同步的。然而,下面作者给出的解决方案的 99% -> https://stackoverflow.com/a/66558251/11781464
fs.readdir
是异步的,只需使其同步 fs.readdirsync
。
以下是更新后的代码,所有功劳都归功于作者 https://stackoverflow.com/a/66558251/11781464。
更新代码
try {
const path = './'
// Read the directory given in `path`
fs.readdirsync(path).forEach((file) => {
// Check if the file is with a PDF extension,remove it
if (file.split('.').pop().toLowerCase() === 'pdf') {
console.log(`Deleting file: ${file}`);
fs.unlinkSync(path + file)
}
});
console.log("Deleted all the pdf files")
return true;
} catch (err) {
console.error("Error in deleting files",err);
}
解决方法
您可以使用 fs.readdir
读取目录,然后检查 PDF 文件并删除它们。像这样:
fs = require('fs');
try {
path = './'
// Read the directory given in `path`
const files = fs.readdir(path,(err,files) => {
if (err)
throw err;
files.forEach((file) => {
// Check if the file is with a PDF extension,remove it
if (file.split('.').pop().toLowerCase() == 'pdf') {
console.log(`Deleting file: ${file}`);
fs.unlinkSync(path + file)
}
});
});
} catch (err) {
console.error(err);
}
,
初步阅读
-
The current working directory of the Node.js process - 查看答案下方的更新
-
Path 方法
resolve
extName
-
File System 方法
fs.readdirSync
fs.unlinkSync
和类
示例
"use strict";
const fs = require('fs');
const path = require('path');
const cwd = process.cwd();
fs.readdirSync( cwd,{withFileTypes: true})
.forEach( dirent => {
if(dirent.isFile()) {
const fileName = dirent.name;
if( path.extname(fileName).toLowerCase() === ".pdf") {
fs.unlinkSync( path.resolve( cwd,fileName));
}
}
});
注意事项
- 未经测试的代码
- 如果
unlinkSync
失败,我会假设它根据文档中链接的 unlink(2) 手册页返回 -1。就我个人而言,我会使用cwd
中不存在的文件名对此进行测试。 - 我相信
{withFileTypes: true}
的readdirSync
选项会返回带有 mime-type 值的dirent
对象,该值允许您检查application/pdf
类型的文件,而不管扩展名(示例中未尝试)。
更新:默认情况下,path(resolve)
在返回路径的开头添加当前工作目录,必要时。 path.resolve(fileName)
与示例中的 path.resolve(cwd,fileName)
一样有效。
您似乎知道如何删除 (unlink
) 文件 - 您是在询问如何获取文件路径?
尝试使用 glob
:
const pdfFiles = require("glob").globSync("*.pdf");
,
嗨,这里我附上了测试代码,用于从目录中删除所有(仅).pdf 文件,而不是其他扩展文件,如 .txt、.docs 等。
注意:您只能从服务器端删除任何文件或目录。
const fs = require('fs');
const path = require('path')
fs.readdir('../path to directory',files) => {
const pdfFiles = files.filter(el => path.extname(el) === '.pdf')
pdfFiles.forEach(file => {
console.log("Removing File -> ",file);
var filename = "../path to directory/"+file;
fs.unlink(filename,function(err){
if(err) return console.log(err);
console.log('file deleted successfully');
});
});
});
这将在控制台日志中为您提供以下结果。
正在删除文件 -> note.pdf
删除文件 -> note2.pdf
文件删除成功
文件删除成功
如果有任何疑问,请随时发表评论..
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。