Skip to content

Commit

Permalink
fix: stop File.download from truncating output file on failure (#1720)
Browse files Browse the repository at this point in the history
* fix: dont overwrite file

* Notes

* cleaned up tests

* 馃 Updates from OwlBot

See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md

Co-authored-by: Daniel Bankhead <danielbankhead@google.com>
Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
  • Loading branch information
3 people committed Nov 22, 2021
1 parent 0c75e33 commit d77979b
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/file.ts
Expand Up @@ -2144,11 +2144,12 @@ class File extends ServiceObject<File> {
const fileStream = this.createReadStream(options);

if (destination) {
fileStream
.on('error', callback)
.pipe(fs.createWriteStream(destination))
.on('error', callback)
.on('finish', callback);
fileStream.on('error', callback).once('data', data => {
// We know that the file exists the server
const writable = fs.createWriteStream(destination);
writable.write(data);
fileStream.pipe(writable).on('error', callback).on('finish', callback);
});
} else {
getStream
.buffer(fileStream)
Expand Down
55 changes: 55 additions & 0 deletions test/file.ts
Expand Up @@ -2697,6 +2697,61 @@ describe('File', () => {
});
});

it('should process the entire stream', done => {
tmp.setGracefulCleanup();
tmp.file(async (err, tmpFilePath) => {
assert.ifError(err);

const fileContents = 'abcdefghijklmnopqrstuvwxyz';

fileReadStream.on('resume', () => {
fileReadStream.emit('data', fileContents);
fileReadStream.emit('data', fileContents);
setImmediate(() => {
fileReadStream.emit('end');
});
});

file.download({destination: tmpFilePath}, (err: Error) => {
assert.ifError(err);
fs.readFile(tmpFilePath, (err, tmpFileContents) => {
assert.ifError(err);
assert.strictEqual(
fileContents + fileContents,
tmpFileContents.toString()
);
done();
});
});
});
});

it('file contents should remain unchanged if file nonexistent', done => {
tmp.setGracefulCleanup();
tmp.file(async (err, tmpFilePath) => {
assert.ifError(err);

const fileContents = 'file contents that should remain unchanged';
fs.writeFileSync(tmpFilePath, fileContents, 'utf-8');

const error = new Error('Error.');
fileReadStream.on('resume', () => {
setImmediate(() => {
fileReadStream.emit('error', error);
});
});

file.download({destination: tmpFilePath}, (err: Error) => {
assert.strictEqual(err, error);
fs.readFile(tmpFilePath, (err, tmpFileContents) => {
assert.ifError(err);
assert.strictEqual(fileContents, tmpFileContents.toString());
done();
});
});
});
});

it('should execute callback with error', done => {
tmp.setGracefulCleanup();
tmp.file((err, tmpFilePath) => {
Expand Down

0 comments on commit d77979b

Please sign in to comment.