LoginSignup
0
0

More than 3 years have passed since last update.

Typescript(Node.js)でtgzを解凍する

Posted at

Typescriptでtgz(tar.gz)ファイルを解凍する

実装例が少ないことと、紹介されている実装方法では展開先などが指定できなかったりするものがあるため、紹介しておきたいと思います。

使用するパッケージ

npm tar

よく見る実装方法

import * as fs from 'fs';
import * as zlib from 'zlib';
import * as tar from 'tar';

const tgzPath = '/file/hoge.tgz';
const outPath  = '/path/output';

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

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

tarパッケージ内でgzipは解凍してくれる

extractメソッドには以下のような説明書きがされている。

/**
 * Extract a tarball archive. The fileList is an array of paths to extract
 * from the tarball. If no paths are provided, then all the entries are
 * extracted. If the archive is gzipped, then tar will detect this and unzip
 * it. Note that all directories that are created will be forced to be
 * writable, readable, and listable by their owner, to avoid cases where a
 * directory prevents extraction of child entries by virtue of its mode. Most
 * extraction errors will cause a warn event to be emitted. If the cwd is
 * missing, or not a directory, then the extraction will fail completely.
 */

よりかんたんな実装

実のところ、以下のコードだけでtar.gzを解凍できる。

import * as tar from 'tar';

tar.x({path:'/file/hoge.tgz', cwd:'/path/output'}

以上

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