在NodeJS中创建一个zip存档

时间:2018-11-15 10:26:26

标签: node.js zip

我是Node.JS的新手,我想在文件夹中搜索特定字符串,并添加在zip存档中找到的所有文件。 示例:我有字符串“ house”,并且在文件夹中有house_1.txt,house_2.txt和car。档案必须包含house_1.txt,house_2.txt。我在Google上搜索了一些内容,但无法完成。

1 个答案:

答案 0 :(得分:0)

由于该代码是同步的,所以它不会伪装成超级快,但是可以。

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`);