7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nodeのストリームで.tar.gzを解凍する方法

Last updated at Posted at 2015-06-01

メモ程度に、.tar.gzのファイルを解凍する方法です。

gunzipの部分はzlibで、tarの中身を取り出すのはnode-tarを使います。

var fs   = require('fs');
var zlib = require('zlib');
var tar  = require('tar');

var tarballPath = '/path/to/my/tarball.tar.gz';
var outputPath  = '/path/to/my/output';

var gunzip    = zlib.createGunzip();
var extractor = tar.Extract({path: outputPath});

fs.createReadStream(tarballPath).pipe(gunzip).pipe(extractor);

で終わります。エラー処理や終わった時のコールバックはパイプの.on('error', cb).on('finish', cb)で簡単に実現できます。

ジェネレーターを使う場合は

ES6のジェネレーターを使うと、コールバックはやや不便ですが、coを使うと、Promiseyieldできるので、パイプをpromiseとして返してくれるライブラリを使うときれいに書けます。

fs.createReadStream(tarballPath).pipe(gunzip).pipe(extractor);

var promisePipe = require('promisepipe');
yield promisePipe(readStream, gunzip, extractor);

に変えれば終わりです。

7
8
2

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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?