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

'use strict';

const zlib = require('zlib');
const tar = require('tar');
const fstream = require('fstream');
const fsp = require('fs-promise');
const fs = require('fs');
const md5File = require('md5-file');

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 {
                    let packer = tar.Pack();

                    let wirte = fstream.Writer({
                            'path': `${dist}`
                        }).on('close', () => {
                            let filecode = md5File.sync(dist);

                            console.log(filecode);
                            reslove(filecode);
                        });

                    fstream.Reader(readCfg) /* Read the source directory */
                        .pipe(packer) /* Convert the directory to a .tar file */
                        .pipe(zlib.Gzip()) /* Compress the .tar file */
                        .pipe(wirte);
                        
                } catch (e) {
                    reject(e);
                }
            });
        })
    }
}

module.exports = Tar;