János János - 6 months ago 11
Node.js Question

Why node.js convert POST body?

Want to save JPG binary body data to file system in

OpenShift
. But somehow received info will get converted. Do you have any idea why? Is it possible that node.js treat data as text and does an encoding / decoding on it?

var myServer = http.createServer(function(request, response)
{
var data = '';

request.on('data', function (chunk){
data += chunk;
});

request.on('end',function(){

var date = new Date();
var url_parts = url.parse(request.url,true);

if(url_parts.pathname == '/setImage') {

if(data != null && data.length > 0) {

fs.writeFile('/var/lib/openshift/555dd1415973ca1660000085/app-root/data/asset/' + url_parts.query.filename, data, 'binary', function(err) {
if (err) throw err
console.log(date + ' File saved. ' + url_parts.query.filename + ' ' + data.length)

response.writeHead(200)
response.end()
})
}
}


enter image description here

Answer

You are initializing data with a string, so adding chunk's with += to it will convert the chunks to string as well (which is subject to character encoding).

Instead, you should collect the chunks as an array of Buffer's and use Buffer.concat() to create the final Buffer:

var chunks = [];

request.on('data', function (chunk){
    chunks.push(chunk);
});

request.on('end', function() {
  var data = Buffer.concat(chunks);
  ...
});
Comments