Skip to content

Commit ae94cb9

Browse files
committed
fix(gridfs-stream): ensure close is emitted after last chunk
NODE-1969
1 parent f49233a commit ae94cb9

File tree

2 files changed

+47
-5
lines changed

2 files changed

+47
-5
lines changed

lib/gridfs-stream/download.js

+12-5
Original file line numberDiff line numberDiff line change
@@ -185,12 +185,19 @@ function doRead(_this) {
185185
}
186186
if (!doc) {
187187
_this.push(null);
188-
return _this.s.cursor.close(function(error) {
189-
if (error) {
190-
return __handleError(_this, error);
191-
}
192-
_this.emit('close');
188+
189+
process.nextTick(() => {
190+
_this.s.cursor.close(function(error) {
191+
if (error) {
192+
__handleError(_this, error);
193+
return;
194+
}
195+
196+
_this.emit('close');
197+
});
193198
});
199+
200+
return;
194201
}
195202

196203
var bytesRemaining = _this.s.file.length - _this.s.bytesRead;

test/functional/gridfs_stream_tests.js

+35
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,41 @@ describe('GridFS Stream', function() {
420420
}
421421
});
422422

423+
it('should emit close after all chunks are received', {
424+
metadata: { requires: { topology: ['single'] } },
425+
426+
test: function(done) {
427+
const configuration = this.configuration;
428+
const GridFSBucket = configuration.require.GridFSBucket;
429+
430+
const client = configuration.newClient(configuration.writeConcernMax(), { poolSize: 1 });
431+
client.connect((err, client) => {
432+
expect(err).to.not.exist;
433+
const db = client.db(configuration.db);
434+
const bucket = new GridFSBucket(db, {
435+
bucketName: 'gridfsdownload',
436+
chunkSizeBytes: 6000
437+
});
438+
439+
const readStream = fs.createReadStream('./LICENSE.md');
440+
const uploadStream = bucket.openUploadStream('teststart.dat');
441+
uploadStream.once('finish', function() {
442+
const downloadStream = bucket.openDownloadStreamByName('teststart.dat');
443+
444+
const events = [];
445+
downloadStream.on('data', () => events.push('data'));
446+
downloadStream.on('close', () => events.push('close'));
447+
downloadStream.on('end', () => {
448+
expect(events).to.eql(['data', 'data', 'close']);
449+
client.close(done);
450+
});
451+
});
452+
453+
readStream.pipe(uploadStream);
454+
});
455+
}
456+
});
457+
423458
/**
424459
* Deleting a file from GridFS
425460
*

0 commit comments

Comments
 (0)