With the code below I am able to upload an image to mogodb one time, if I try a second time I get an error.
I did some research and its because the writestream is closing NODEJS writeStream error
conn.once('open', function () {
var gfs = Grid(conn.db, mongoose.mongo);
app.post('/upload', function(req,res){
form.on('part', function(part){
if(!part.filename) return;
size = part.byteCount;
fileName = part.filename;
});
form.on('file', function(name,file){
var tempfile = file.path;
var origname = fileName;
var writestream = gfs.createWriteStream({ filename: origname });
fs.createReadStream(tempfile).on('end', function () {
res.send('<p><h1>Upload Complete!</h1><p>');
}).on('error', function () {
res.send('Error, upload failed!');
}).pipe(writestream);
});
form.parse(req);
});
app.get('/image/:id', function(req,res){
console.log(req.params.id)
gfs.createReadStream({_id:req.params.id}).pipe(res);
});
});
The error message looks like this
events.js:72
throw er; // Unhandled 'error' event
^
Error: write after end
at writeAfterEnd (C:\Users\Michael\Desktop\Chat-App\node_modules\multiparty\node_modules\readable-stream\lib\_stream_writable.js:161:12)
at Form.Writable.write (C:\Users\Michael\Desktop\Chat-App\node_modules\multiparty\node_modules\readable-stream\lib\_stream_writable.js:208:5)
at write (_stream_readable.js:582:24)
at flow (_stream_readable.js:591:7)
at _stream_readable.js:559:7
at process._tickCallback (node.js:419:13)
So it looks like multiparty is problematic with my code. My question is how do I solve this should I change my post method to run the code on an id?