lib/targz-glob-stream.js (47 lines of code) (raw):

const Promise = require('bluebird'); const path = require('path'); const fs = require('fs-extra'); const stat = Promise.promisify(fs.stat); const glob = Promise.promisify(require('glob')); const tarstream = require('tar-stream'); const zlib = require('zlib'); function targzGlobStream(globString, options) { const stream = tarstream.pack(); const addFileToStream = (filePath, size) => { return new Promise((resolve, reject) => { const entry = stream.entry({ name: path.relative(options.base || '', filePath), size: size }, (err) => { if(err) reject(err); resolve(); }); fs.createReadStream(filePath) .pipe(entry); }); }; const getFileMap = glob(globString, Object.assign({ nodir: true }, options)) .then((files) => { const fileMap = {}; const stattingFilePromises = files.map((file) => { return stat(file) .then((fileStats) => { fileMap[file] = fileStats; }); }); return Promise.all(stattingFilePromises) .then(() => fileMap); }); getFileMap.then((fileMap) => { // We can only add one file at a time return Object.keys(fileMap).reduce((promiseChain, file) => { return promiseChain.then(() => { return addFileToStream(file, fileMap[file].size); }); }, Promise.resolve()); }) .then(() => { stream.finalize(); }); return stream.pipe(zlib.createGzip()); } module.exports = targzGlobStream;