Skip to content

Commit

Permalink
fix(gridfs-stream): ensure close is emitted after last chunk
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Aug 26, 2019
1 parent f49233a commit ae94cb9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
17 changes: 12 additions & 5 deletions lib/gridfs-stream/download.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,12 +185,19 @@ function doRead(_this) {
}
if (!doc) {
_this.push(null);
return _this.s.cursor.close(function(error) {
if (error) {
return __handleError(_this, error);
}
_this.emit('close');

process.nextTick(() => {
_this.s.cursor.close(function(error) {
if (error) {
__handleError(_this, error);
return;
}

_this.emit('close');
});
});

return;
}

var bytesRemaining = _this.s.file.length - _this.s.bytesRead;
Expand Down
35 changes: 35 additions & 0 deletions test/functional/gridfs_stream_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,41 @@ describe('GridFS Stream', function() {
}
});

it('should emit close after all chunks are received', {
metadata: { requires: { topology: ['single'] } },

test: function(done) {
const configuration = this.configuration;
const GridFSBucket = configuration.require.GridFSBucket;

const client = configuration.newClient(configuration.writeConcernMax(), { poolSize: 1 });
client.connect((err, client) => {
expect(err).to.not.exist;
const db = client.db(configuration.db);
const bucket = new GridFSBucket(db, {
bucketName: 'gridfsdownload',
chunkSizeBytes: 6000
});

const readStream = fs.createReadStream('./LICENSE.md');
const uploadStream = bucket.openUploadStream('teststart.dat');
uploadStream.once('finish', function() {
const downloadStream = bucket.openDownloadStreamByName('teststart.dat');

const events = [];
downloadStream.on('data', () => events.push('data'));
downloadStream.on('close', () => events.push('close'));
downloadStream.on('end', () => {
expect(events).to.eql(['data', 'data', 'close']);
client.close(done);
});
});

readStream.pipe(uploadStream);
});
}
});

/**
* Deleting a file from GridFS
*
Expand Down

0 comments on commit ae94cb9

Please sign in to comment.