aheckmann / gridfs-stream

Easily stream files to and from MongoDB
MIT License
615 stars 120 forks source link

GridWriteStream emits uncatchable error in constructor #95

Open zolern opened 8 years ago

zolern commented 8 years ago

GridWriteStream.prototype._open emit error event if error is occured in this._store.open.

This cause uncatchable error while calling createWriteStream routines:

var mongo = require('mongodb');
var Grid = require('gridfs-stream');

// create or use an existing mongodb-native db instance
var db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017));
var gfs = Grid(db, mongo);

// streaming to gridfs
var writestream = gfs.createWriteStream({
    filename: 'my_file.txt'
});
writeStream.on("error", function(err) { //not called if error occured in createWriteStream
  console.log('An error occurred!, err);
});
fs.createReadStream('/some/path').pipe(writestream);

As a result nodeJS process is terminated with unhadled exception.

I propose to add 'postponed' parameter in GridWriteStream.prototype._error. For example:

GridWriteStream.prototype._error = function _error (err, postponed) {
    // Stop receiving more data to write, emit `error` and close the store
    if (this._errorEmitted) return;
    this._errorEmitted = true;

    this._writable = false;
    if (postponed) {
        setImmediate(function() { this.emit('error', err); }); 
    } else {
        this.emit('error', err);
    }
    this._close();
}

And change call of this._error in GridWriteStream.prototype._open, as follows:

...
    this._store.open(function (err, gs) {
        self._opening = false;
        if (err) return self._error(err, true);
        self._opened = true;
...