【问题标题】:For loop that gets file names from specified folder and all subfolders - js从指定文件夹和所有子文件夹获取文件名的循环 - js
【发布时间】:2021-08-24 16:54:07
【问题描述】:

我有两个js脚本想合并成一个,但是不知道怎么做。

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

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

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

我该怎么做呢?

脚本一:

/*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));

【问题讨论】:

    标签: javascript node.js for-loop


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      相关资源
      最近更新 更多