Request: How to save downloaded binary data without using pipe

Created on 19 Jan 2017  ·  3Comments  ·  Source: request/request

On my node server and try to download a png image from a url and write it to a file:

.get("https://url/for/png/file")
.on('error', function(err) {
  console.log(err)
})
.on('response', function(response){
  console.log(response.statusCode) // 200
  console.log(response.headers['content-type']); // 'image/png'
})
.on('complete', (resp: http.IncomingMessage, body: string | Buffer) => {
  fs.writeFile(".../test.png", body, 'binary');

});

The main issue is that the written file is corrupted (can't be opened).

If I use pipe instead of on('complete'...) at the end the written file is correct.

.pipe(fs.createWriteStream(".../test.png"))

What exactly is the difference and what am I missing to be able to write the file?

Most helpful comment

use encoding: null option

All 3 comments

The same problem.

use encoding: null option

@lambdacerro Thank you, will close this issue then.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danielgindi picture danielgindi  ·  20Comments

ovk picture ovk  ·  26Comments

dcsan picture dcsan  ·  19Comments

maiko-rocha picture maiko-rocha  ·  51Comments

pho3nixf1re picture pho3nixf1re  ·  41Comments