title: NodeJS - reading Image Binary File
body: <p>I am working on the API for store a file uploaded by the user.</p>
  <pre><code>function uploadPhoto(req, res) {
      var imagedata = new Buffer('');
  
      req.body.on('data', function (chunk) {
          imagedata = Buffer.concat([imagedata, chunk]);
      });
      req.body.on('end', function (chunk) {
          fs.writeFile('success.jpeg', imagedata, 'binary', function (err) {
              if (err) throw err
              console.log('File saved.')
          })
      });
  }
  </code></pre>
  <p>There is an error when I used req.body.on('data').
  The data from postman
  <a href="https://i.stack.imgur.com/kyWnf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kyWnf.png" alt="enter image description here" /></a>
  <a href="https://i.stack.imgur.com/BIwFi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BIwFi.png" alt="enter image description here" /></a></p>
  <p>When I print out the value of req.body with console.log(&quot;message: &quot;+req.body), it was string and has value:
  <a href="https://i.stack.imgur.com/vatyC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vatyC.png" alt="enter image description here" /></a></p>
  <p>I tried to write to file by using Buffer like this</p>
  <pre><code>var writeFile = function (type, cb) {
      var data = new Buffer(req.body, type);
      fs.writeFile(type + '.jpeg', data, type, function (err) {
          cb(null, data.length);
      });
  }
  async.parallel([
        writeFile.bind(null, 'binary'),
        writeFile.bind(null, 'utf8'),
        writeFile.bind(null, 'ascii'),
        writeFile.bind(null, 'ucs2'),
        writeFile.bind(null, 'base64')
     ], function (err, results) {
        response.status(200).send({});
     })
  </code></pre>
  <p>This will create some jpeg files with different size but can't read them as an image.</p>
  <p>How can I store this image from the user?
  Thank you very much.</p>