János János - 2 years ago 134
Node.js Question

Why node.js convert POST body?

Want to save JPG binary body data to file system in

. 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;


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)


enter image description here

Answer Source

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){

request.on('end', function() {
  var data = Buffer.concat(chunks);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download