Z
Z
zzox42016-05-01 19:58:50
Node.js
zzox4, 2016-05-01 19:58:50

Why does nodejs break data when downloading and saving a file?

The goal is to get a Buffer with data, but when downloading it contains crooked data, if you save it to a file, then the file contains trash instead of a picture.
What is the problem? node v4.3.1 Whole code:

var request = require('request');
var fs = require('fs');

var url = 'http://codewinds.com/assets/codewinds/codewinds-podcast-200.png';
console.log('START', url);

request.get(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log('LENGTH', body.length);

        fs.writeFile("11111.png", body, function(err) {
            if(err) {
                return console.log(err);
            }
        });
    };
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
zzox4, 2016-05-01
@zzox4

In general, you need to reset the encoding: defaults({encoding: null})
otherwise it encodes the picture in utf8% -\

A
Alexey, 2016-05-01
@alsopub

Maybe

fs.writeFile("11111.png", body, 'binary', function(err) {
            if(err) {
                return console.log(err);
            }
        });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question