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

xin7c picture xin7c  路  3Comments

pixarfilmz112 picture pixarfilmz112  路  3Comments

jdarling picture jdarling  路  3Comments

ghost picture ghost  路  3Comments

jasonxia23 picture jasonxia23  路  3Comments