5

I'm receiving an image in a binary stream as shown below, however when I try to create a buffer with the following data the buffer appears to be empty. Is the problem that buffer doesn't understand this format?

V�q)�EB\u001599!F":"����\u000b��3��5%�L�\u0018��pO^::�~��m�<\u001e��L��k�%G�$b\u0003\u0011���=q�V=��A\u0018��O��U���m�B���\u00038�����0a�_��#\u001b����\f��(�3�\u0003���nGjr���Mt\�\u0014g����~�#�Q�� g�K��s��@C��\u001cS�`\u000bps�Gnzq�Rg�\fu���C\u0015�\u001d3�E.BI\u0007���

var buffer = new Buffer(req.body, 'binary')
    console.log("BUFFER:" + buffer)
fs.writeFile('test.jpg', buffer, function(err,written){
   if(err) console.log(err);
    else {
     console.log("Successfully written");
    }
});

2 Answers 2

1

I think you should set the encoding when you call fs.writeFile like this :

fs.writeFile('test.jpg', buffer, 'binary', function(err) {
Sign up to request clarification or add additional context in comments.

4 Comments

problem occurs before that I believe. When I log buffer it is empty and buffer.length returns 0 as well.
Then may be req.body is empty ?
what I put in the quote I directly copied from logging out req.body.
Did you check the buffer byteLength?
1

Problem was body-parser doesn't parse content-type: octet-stream and I was overriding the header to parse it as an url-encoded-form which the buffer didn't understand even though I was able to log the req.body. The middleware below allows for the parsing of content-type: octet-stream for body-parser.

app.use(function(req, res, next) {
   var contentType = req.headers['content-type'] || ''
   var mime = contentType.split(';')[0];
    // Only use this middleware for content-type: application/octet-stream
    if(mime != 'application/octet-stream') {
        return next();
    }
   var data = '';
   req.setEncoding('binary');
    req.on('data', function(chunk) { 
       data += chunk;
   });
   req.on('end', function() {
      req.rawBody = data;
      next();
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.