tar.js 1.31 KB
/**
 * zip/unzip folder
 * 
 * @author: jf<jeff.jiang@yoho.com>
 * @date: 2016/5/20
 */

'use strict';

import zlib from 'zlib';
import tar from 'tar';
import fstream from 'fstream';
import fsp from 'fs-promise';
import fs from 'fs';

class Tar {

    static gzip(target, dist) {
        console.log(`gzip ${target} to ${dist}`);

        return fsp.stat(target).then((stats) => {
            let readCfg = {
                path: target
            };
            if (!stats) {
                return Promise.reject(`gzip target file is not exists: ${target}`);
            } else if (stats.isDirectory()) {
                readCfg.type = 'Directory';
            } else if (stats.isFile()) {
                readCfg.type = 'File';
            }

            return new Promise((reslove, reject) => {
                try {
                    fstream.Reader(readCfg) /* Read the source directory */
                        .pipe(tar.Pack()) /* Convert the directory to a .tar file */
                        .pipe(zlib.Gzip()) /* Compress the .tar file */
                        .pipe(fstream.Writer({
                            'path': `${dist}`
                        }));
                    reslove();
                } catch (e) {
                    reject(e);
                }
            });
        })
    }
}

export default Tar;