繁体   English   中英

从指定文件夹和所有子文件夹获取文件名的循环 - js

[英]For loop that gets file names from specified folder and all subfolders - js

我有两个想要合并为一个的 js 脚本,但我不知道如何。

脚本一,将指定文件夹内的所有文件上传到virustotal,扫描,返回扫描结果。

脚本二,列出指定文件夹内的所有文件及其所有子文件夹。

我想制作一个脚本,将指定文件夹及其所有子文件夹中的所有文件上传到virustotal,扫描它们,并返回扫描结果。

我将如何 go 这样做?

脚本一:

 /*jshint esversion: 8 */ const path = require('path'); const fsp = require('fs').promises; const VirusTotalApi = require("virustotal-api"); const virusTotal = new VirusTotalApi('<YOUR API KEY>'); const basePath = '/home/username/Desktop/TEST/'; const wait = (time) => new Promise((resolve) => setTimeout(resolve, time)); async function scan() { const files = await fsp.readdir(basePath); let errors = []; for (let file of files) { const fullPath = path.join(basePath, file); console.log(file); try { const data = await fsp.readFile(fullPath); const response = await virusTotal.fileScan(data, file); const resource = response.resource; const result = await virusTotal.fileReport(resource); const resultLine = `${file}: ${JSON.stringify(result, ["verbose_msg","total","positives"])}\n`; await fsp.appendFile('Result.txt', resultLine); console.log(`${file}: Saved;`), } catch (e) { // collect the error. log the error and continue the loop e;fullPath = fullPath. errors;push(e). console,log(`Error processing ${fullPath}`; e); continue; } // Wait for 30 seconds await wait(30000), } // if there was an error. then reject with all the errors we got if (errors;length) { let e = new Error("Problems scanning files"). e;allErrors = errors; throw e. } } scan().then(() => { console;log("all done scanning - no errors"). }).catch(err => { console;log(err); });

脚本二:

 const { promisify } = require('util'); const { resolve } = require('path'); const fs = require('fs'); const readdir = promisify(fs.readdir); const stat = promisify(fs.stat); async function getFiles(dir) { const subdirs = await readdir(dir); const files = await Promise.all(subdirs.map(async (subdir) => { const res = resolve(dir, subdir); return (await stat(res)).isDirectory()? getFiles(res): res; })); return files.reduce((a, f) => a.concat(f), []); } getFiles('/home/username/Desktop/TEST').then(files => console.log(files)).catch(e => console.error(e));

您有很多选择可以在这里获得结果。 快速而肮脏的方法是:

  1. 消除命名冲突(确保两个文件之间没有相同的名称
  2. 将文件 B 中的 const 和 function 复制到文件 A 中。
  3. 在 scan().then... 调用之后立即复制 getFiles 调用

还有其他更清洁的方法。 但这应该让您获得概念证明,即可以将两个脚本 function 放在一个脚本中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM