Создание zip-архива в NodeJS - PullRequest
0 голосов
/ 15 ноября 2018

Я новичок в Node.JS и хочу выполнить поиск в папке по определенной строке и добавить все файлы, найденные в zip-архиве. Пример: у меня есть строка "дом" и в папке у меня есть house_1.txt house_2.txt и автомобиль. Архив должен содержать house_1.txt, house_2.txt. Я что-то искал в Google, но не смог.

1 Ответ

0 голосов
/ 15 ноября 2018

Этот код не претендует на то, чтобы быть очень быстрым, поскольку он синхронный, но он работает.

const JSZip = require("jszip");
const path = require('path');
const fs = require('fs');

const isDirectory = (filePath) => fs.statSync(filePath).isDirectory();

const findFiles = (dir, fileNames, recursive = false) => {
  const foundFiles = [];

  fs.readdirSync(dir).forEach(file => {
    const filePath = path.join(dir, file);

    if(recursive && isDirectory(filePath)) {
      foundFiles.push(...findFiles(filePath, fileNames, true));

    } else if(fileNames.includes(file)){
      foundFiles.push(filePath);
    }
  });

  return foundFiles;
};

const getFileName = filePath => filePath.indexOf("/") !== -1 ?
    filePath.substr(filePath.lastIndexOf("/")) : filePath;

const zipFiles = (filePaths, zipPath) => {
  const zip = new JSZip();
  filePaths.forEach(filePath => {
    const fileName = getFileName(filePath) + "_" + Date.now();
    const content = fs.readFileSync(filePath);
    zip.file(fileName, content);
  });

  zip.generateNodeStream({type: 'nodebuffer', streamFiles: true})
      .pipe(fs.createWriteStream(zipPath))
      .on('finish', () => console.log(`${zipPath} has been created.`));
};

const filesDir = `${__dirname}/../resources`;
zipFiles(findFiles(filesDir, ["test1.txt"], true), `${filesDir}/out.zip`);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...