hush: wait for close event instead of finish event

use stream.pipeline to cover all the corner cases
This commit is contained in:
Girish Ramakrishnan
2023-08-29 11:44:52 +05:30
parent 6b30b6211a
commit 35828fe1c7

View File

@@ -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;
}