Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems in writing binary data with node.js

I am trying to write the binary body of a request to a file and failing. The file is created on server but I am unable to open it. I am getting 'Fatal error: Not a png' on Ubuntu. Here is how I am making the request:

curl --request POST --data-binary "@abc.png" 192.168.1.38:8080

And here is how I am trying to save it with the file. The first snippet is a middleware for appending all the data together and second one is the request handler:

Middleware:

app.use(function(req, res, next) {
  req.rawBody = '';
  req.setEncoding('utf-8');
  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });
  req.on('end', function() {
    next();
  });
});

Handler:

exports.save_image = function (req, res) {
  fs.writeFile("./1.png", req.rawBody, function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log("The file was saved!");
    }
  });
  res.writeHead(200);
  res.end('OK\n');
};

Here's some info which might help. In the middleware, if I log the length of rawBody, it looks to be correct. I am really stuck at how to correctly save the file. All I need is a nudge in the right direction.

like image 906
Akash Avatar asked Mar 19 '14 12:03

Akash


People also ask

How do I write a binary file in node js?

writeFile("test. txt", b, "binary",function(err) { if(err) { console. log(err); } else { console. log("The file was saved!"); } });

Is heavily used in Node js to deal with stream of binary data?

Buffer is an object property on Node's global object, which is heavily used in Node to deal with streams of binary data. As it is globally available, there is no need to require it in our code. Buffer is actually a chunk of memory allocated outside of the V8 heap.

Where Nodejs should not be used?

Node. js will never be “the best choice” for event loop-blocking use cases (take asynchronous parsing XML, for instance) … nor for powering apps relying on intense computation.


1 Answers

Here is a complete express app that works. I hit it with curl --data-binary @photo.jpg localhost:9200 and it works fine.

var app = require("express")();
var fs = require("fs");
app.post("/", function (req, res) {
  var outStream = fs.createWriteStream("/tmp/upload.jpg");
  req.pipe(outStream);
  res.send();
});
app.listen(9200);

I would just pipe the request straight to the filesystem. As to your actual problem, my first guess is req.setEncoding('utf-8'); as utf-8 is for text data not binary data.

like image 57
Peter Lyons Avatar answered Oct 21 '22 02:10

Peter Lyons