I'm trying to make file uploading to mongodb's gridfs in nodejs. Here's a piece of my code:
var fs = require('fs');
var gridfs = require('gridfs-stream');
var mongo = require('mongodb');
var gfs;
mongo.Db.connect('mongodb://...', function (err, db) {
console.log('*** connect to upload files');
gfs = gridfs(db, mongo);
var fpath = req.files.image_file.path;
var fname = id + '_' + req.files.image_file.name;
console.log('*** final name = ' + fname);
var writestream = gfs.createWriteStream({ filename: fname });
var readstream = fs.createReadStream(fpath);
readstream.on('open', function () {
console.log('*** stream opened');
readstream.pipe(writestream);
});
readstream.on('end', function () {
console.log('*** file upload finished');
doCSUpdate();
});
readstream.on('error', function() {
console.log('*** error occured');
doCSUpdate();
});
});
doCSUpdate()
is some other function.
The problem is that in logs I see that file upload finished
appears twice while stream opened
only once
13:21:30 web.1 | *** connect to upload files
13:21:30 web.1 | *** final name = ...
13:21:30 web.1 | *** stream opened
13:21:30 web.1 | *** file upload finished
13:21:30 web.1 | *** file upload finished
This causes doCSUpdate()
to be run twice which sometimes leads to Can't set headers after they are sent
error because the response is set two times..