LoginSignup
0
0

Node.js で ZIP ファイルを圧縮する方法はをまとめてみました!

方法 1: archiver を使用する方法

archiverは、Node.jsでZIPファイルを圧縮するための強力なライブラリです。

インストール

npm install archiver

使用例

const fs = require('fs');
const archiver = require('archiver');

function zipDirectory(sourceDir, outPath) {
  const output = fs.createWriteStream(outPath);
  const archive = archiver('zip', {
    zlib: { level: 9 } // 圧縮レベル
  });

  output.on('close', () => {
    console.log(`ZIP file has been written. Total size: ${archive.pointer()} bytes.`);
  });

  archive.on('error', (err) => {
    throw err;
  });

  archive.pipe(output);
  archive.directory(sourceDir, false);
  archive.finalize();
}

// 使用例
zipDirectory('path/to/sourceDir', 'path/to/output.zip');

方法 2: adm-zip を使用する方法

adm-zipは、Node.jsでZIPファイルを操作するための簡単なライブラリです。

インストール

npm install adm-zip

使用例

const AdmZip = require('adm-zip');

function zipFiles(sourceFiles, outPath) {
  const zip = new AdmZip();

  sourceFiles.forEach((filePath) => {
    zip.addLocalFile(filePath);
  });

  zip.writeZip(outPath);
  console.log(`ZIP file has been written to ${outPath}`);
}

// 使用例
zipFiles(['path/to/file1.txt', 'path/to/file2.txt'], 'path/to/output.zip');

さいごに

以下まとめになります、

  • archiver: 強力で大規模なディレクトリの圧縮に最適な強力なライブラリですが、実装の流れがちょっと追いにくいです。
  • adm-zip: シンプルで使いやすい印象です!実装の流れも追いやすいです!
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0