Busboy and GridFS will not save the file to the file system

When the following POST API is called, it must save the file to the file system. However, the file is not saved. I see the file in the console, but I can not save or write it. I have the following code:

router.post('/notes', function(req, res, next) { var gfsstream, startFileWrite, endFileWriteTime; var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { startFileWrite = new Date().getTime(); console.log('File [' + fieldname + ']: filename: ' + filename); gfsstream = gfs.createWriteStream('/uploads'); file.on('data', function(data) { gfsstream.write(data); }); file.on('end', function() { gfsstream.end(); req.pipe(gfsstream); }); gfsstream.on('close', function (file) { // do something with `file` endFileWrite = new Date().getTime(); console.log('File [' + fieldname + '] Finished'); console.log("Time needed: " + (endFileWrite - startFileWrite) + " ms"); }); }); busboy.on('error', function(err) { console.error(err); res.sendStatus(500, 'ERROR', err); }); busboy.on('finish', function end() { res.sendStatus(200); }); req.pipe(busboy); }); 

req.pipe(gfsstream) may be the problem here, but I'm not sure what is stopping the file from being saved.

+8
javascript
source share
1 answer

Just execute file.pipe(gfsstream) and use the finish event instead of the close event:

 busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { startFileWrite = new Date().getTime(); console.log('File [' + fieldname + ']: filename: ' + filename); gfsstream = gfs.createWriteStream('/uploads'); file.pipe(gfsstream).on('finish', function() { endFileWrite = new Date().getTime(); console.log('File [' + fieldname + '] Finished'); console.log("Time needed: " + (endFileWrite - startFileWrite) + " ms"); }); }); 
+1
source share

All Articles