LoginSignup
1

More than 3 years have passed since last update.

Node.jsで指定したディレクトリをZIP圧縮するサンプル (async/awaitを用いて書く)

Posted at

Node.jsで指定したディレクトリをZIP圧縮するためのサンプルコードとなります。
async/awaitを用いて書いてみます。

なお、圧縮処理には archiverというnpmライブラリを利用します。

下記のような状況を想定しています。
ここのdirdir.zipにするイメージです。

dir
├── sample1.mp4
├── sample1.mov
└── sample2.mov

サンプルコード

archiverをインストール

yarn add archiver

なるべくシンプルに書こうと思い、削れるところは削ってみています。
archiver 自体の細かな使い方は公式を参照してみてください。

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

const zipArchive = async targetDir => {
  const zipPath = `${targetDir}.zip`;
  const output = fs.createWriteStream(path.join(__dirname, zipPath));

  const archive = archiver('zip', {
    zlib: { level: 9 }
  });

  archive.pipe(output);

  archive.glob(path.join(targetDir, '*.mp4'));
  archive.glob(path.join(targetDir, '*.mov'));

  await archive.finalize();

  return;
}

(async() => {
  await zipArchive('dir');
})();

圧縮する際のオプションについて(archiver)

  const archive = archiver('zip', {
    zlib: { level: 9 }
  });

この記述はREADMEに記述されていたものをそのまま拝借していますが、ここの指定により圧縮率が異なるようです。
ためしにここのオプションをなしにしてみたところ、ZIP圧縮時の容量がやや大きくなりました。
(圧縮するデータにもよるかと思いますが、自身の場合は0.5MBほど大きくなりました)

該当するドキュメントはここあたりになるかと思います。
https://www.archiverjs.com/archiver
https://www.archiverjs.com/global.html#ZipOptions

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
What you can do with signing up
1