Typescriptでtgz(tar.gz)ファイルを解凍する
実装例が少ないことと、紹介されている実装方法では展開先などが指定できなかったりするものがあるため、紹介しておきたいと思います。
使用するパッケージ
よく見る実装方法
import*asfsfrom'fs';import*aszlibfrom'zlib';import*astarfrom'tar';consttgzPath='/file/hoge.tgz';constoutPath='/path/output';constgunzip=zlib.createGunzip();constextractor=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*astarfrom'tar';tar.x({path:'/file/hoge.tgz',cwd:'/path/output'}
以上