Node.JS重定向后将文件下载到服务器

时间:2016-11-11 16:02:15

标签: node.js http facebook-graph-api

我正在尝试使用Node.JS下载Facebook个人资料图片,但我遇到了问题,因为Facebook会进行重定向。

网址 https://graph.facebook.com/userId/picture?type=large

我的下载功能:

var fs = require('fs');
var https = require('follow-redirects').https;

var download = function(uri, filename) {
    var deferred = Q.defer();

    var data = "";
    https.get(uri, function(response) {
        response.on('data', function(chunk) {
            console.log(chunk);
            data += chunk;
        });

        response.on('end', function() {
            fs.writeFile(filename, data, 'binary', function(err) {
                if(err) {
                    console.log(err.message);
                } else {
                    deferred.resolve();
                }
            })
        });

    }).on('error', function(err) {
        fs.unlink(filename);
        deferred.reject(err);
    });

    return deferred.promise;
};

我只获得一个块,因此生成的文件已损坏。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

试试这个:

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

function download(uri, filename) {
    var protocol = url.parse(uri).protocol.slice(0, -1);
    var deferred = Q.defer();
    var onError = function (e) {
        fs.unlink(filename);
        deferred.reject(e);
    }
    require(protocol).get(uri, function(response) {
        if (response.statusCode >= 200 && response.statusCode < 300) {
            var fileStream = fs.createWriteStream(filename);
            fileStream.on('error', onError);
            fileStream.on('close', deferred.resolve);
            response.pipe(fileStream);
        } else if (response.headers.location) {
            deferred.resolve(download(response.headers.location, filename));
        } else {
            deferred.reject(new Error(response.statusCode + ' ' + response.statusMessage));
        }
    }).on('error', onError);
    return deferred.promise;
};