Search code examples
javascriptnode.jsmongodbbusboy

How to convert busboy file stream to binary object on nodejs


Requirement: Working on image file upload. Here, using express and node.js. Received binary data in file using busboy package.

My question is how to receive binary data from file to local variable to insert in mongo db.

var binaryData = "";

var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
  file.pipe(/********want to receive binary data to binaryData************/); 
});

How to get binary data into binaryData variable?

Any alternative approach to receive file content to write directly on mongodb (not gridfs).

Thank you.


Solution

  • You can pipe to any writable stream or if you want to handle the data yourself (for buffering purposes or otherwise), you can use the 'data' and 'end' events or use file.read() and the 'readable' event to manually read data from the stream. The data in the file stream is typically binary, but you will have to check encoding and/or mimetype to be sure.