You are trying to read an empty file. Check your code to download the file from disk and check the PDF file.
An empty binary will look like this:
> console.log(new mongodb.Binary("")); { _bsontype: 'Binary', sub_type: 0, position: 0, buffer: <Buffer > }
The content binary will look something like this:
{ _bsontype: 'Binary', sub_type: 0, position: 7867, buffer: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 c3 a4 c3 bc c3 b6 c3 ...> }
Here is a complete example that worked for me:
var fs = require('fs'); var mongo = require('mongodb').MongoClient; var pdfBinary = fs.readFileSync("testout.pdf"); // print it out so you can check that the file is loaded correctly console.log("Loading file"); console.log(pdfBinary); var invoice = {}; invoice.pdf = new mongodb.Binary(pdfBinary); // set an ID for the document for easy retrieval invoice._id = 12345; mongo.connect('mongodb://127.0.0.1:27017/test', function(err, db) { if(err) console.log(err); db.collection('invoices').insert(invoice, function(err, doc){ // check the inserted document console.log("Inserting file"); console.log(doc); db.collection('invoices').findOne({_id : 12345}, function(err, doc){ if (err) console.error(err); fs.writeFile('testout.pdf', doc.pdf.buffer, function(err){ if (err) throw err; console.log('Sucessfully saved!'); }); }); }); });
I added console.log() commands so you can easily see where the problem is.
source share