diff --git a/src/hush.js b/src/hush.js index b6f1ff74a..772c93315 100644 --- a/src/hush.js +++ b/src/hush.js @@ -6,6 +6,7 @@ const assert = require('assert'), debug = require('debug')('box:hush'), fs = require('fs'), ProgressStream = require('./progress-stream.js'), + stream = require('stream'), TransformStream = require('stream').Transform; class EncryptStream extends TransformStream { @@ -184,32 +185,28 @@ function createWriteStream(destFile, encryption) { assert.strictEqual(typeof destFile, 'string'); assert.strictEqual(typeof encryption, 'object'); - const stream = fs.createWriteStream(destFile); + const destStream = fs.createWriteStream(destFile); const ps = new ProgressStream({ interval: 10000 }); // display a progress every 10 seconds - stream.on('error', function (error) { - debug(`createWriteStream: write stream error ${destFile}. %o`, error); - ps.emit('error', new BoxError(BoxError.FS_ERROR, `Write error ${destFile}: ${error.message}`)); - }); - - stream.on('finish', function () { - debug('createWriteStream: done.'); - // we use a separate event because ps is a through2 stream which emits 'finish' event indicating end of inStream and not write - ps.emit('done'); - }); + const streams = [ ps ]; if (encryption) { - let decrypt = new DecryptStream(encryption); - decrypt.on('error', function (error) { - debug(`createWriteStream: decrypt stream error ${destFile}. %o`, error); - ps.emit('error', new BoxError(BoxError.CRYPTO_ERROR, `Decryption error at ${destFile}: ${error.message}`)); - }); - - ps.pipe(decrypt).pipe(stream); - } else { - ps.pipe(stream); + const decryptStream = new DecryptStream(encryption); + streams.push(decryptStream); } + streams.push(destStream); + + stream.pipeline(streams, function (error) { + if (error) { + debug(`createWriteStream: write stream error ${destFile}. %o`, error); + ps.emit('error', new BoxError(BoxError.FS_ERROR, `Write error ${destFile}: ${error.message}`)); + } else { + debug(`createWriteStream: ${destFile} done`); + return ps.emit('done'); + } + }); + return ps; }