0

I am tryint to donwload a binary file via http in nodejs. Inspired by this question, I tried this:

http.get(url,function (res) {
    res.setEncoding('binary');
    var body = [];
    res.on("data", function (chunk) {
        body.push(chunk);
    });
    res.on("end", function () {
        result = Buffer.concat(body);
    });
});

The problem is, that the chunk data blocks are of type string, not of type buffer. For this reasons Buffer.concat(body) fails.

Why and how can I change this?

Community
  • 1
  • 1
Nathan
  • 7,099
  • 14
  • 61
  • 125
  • 1
    This question and answer may be helpful to solving your issue: http://stackoverflow.com/a/35854678/5884189 – mmryspace May 25 '16 at 14:35

2 Answers2

2

The reason why the "chunks" are of type string is actually because I am calling setEncoding. If I remove that line, it works:

http.get(url,function (res) {
    //res.setEncoding('binary');
    var body = [];
    res.on("data", function (chunk) {
        body.push(chunk);
    });
    res.on("end", function () {
        result = Buffer.concat(body);
    });
});
Nathan
  • 7,099
  • 14
  • 61
  • 125
1

If you want to stick with using Buffer can you use the Buffer.from() function.

http.get(url,function (res) {
    res.setEncoding('binary');
    var body = [];
    res.on("data", function (chunk) {
        body.push(chunk);
    });
    res.on("end", function () {
        result = Buffer.concat(Buffer.from(body));
    });
});
Ant Kennedy
  • 1,230
  • 7
  • 13