在获取node.js的二进制内容与http.request [英] Getting binary content in node.js with http.request

查看:1146
本文介绍了在获取node.js的二进制内容与http.request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个HTTPS请求检索二进制数据。

I would like to retrieve binary data from an https request.

我发现了一个类似的问题使用请求方法,
<一href=\"http://stackoverflow.com/questions/14855015/getting-binary-content-in-node-js-using-request\">Getting在Node.js的二进制内容使用申请,是说设置的编码无效应该工作,但它没有。

I found a similar question that uses the request method, Getting binary content in Node.js using request, is says setting encoding to null should work, but it doesn't.

options = {
hostname: urloptions.hostname,
path: urloptions.path,
method: 'GET',
rejectUnauthorized: false,
encoding: null
};

req = https.request(options, function(res) {
var data;
data = "";
res.on('data', function(chunk) {
    return data += chunk;
});
res.on('end', function() {
    return loadFile(data);
});
res.on('error', function(err) {
    console.log("Error during HTTP request");
    console.log(err.message);
});
})

编辑:设置编码的'二进制'无法正常工作或

推荐答案

接受的答案对我来说没有工作(即设置编码为二进制),甚至是谁问的问题中提到它不工作的用户。

The accepted answer did not work for me (i.e., setting encoding to binary), even the user who asked the question mentioned it did not work.

这里是为我工作,摘自:<一href=\"http://chad.pantherdev.com/node-js-binary-http-streams/\">http://chad.pantherdev.com/node-js-binary-http-streams/

Here's what worked for me, taken from: http://chad.pantherdev.com/node-js-binary-http-streams/

http.get(url.parse('http://myserver.com:9999/package'), function(res) {
    var data = [];

    res.on('data', function(chunk) {
        data.push(chunk);
    }).on('end', function() {
        //at this point data is an array of Buffers
        //so Buffer.concat() can make us a new Buffer
        //of all of them together
        var buffer = Buffer.concat(data);
        console.log(buffer.toString('base64'));
    });
});

编辑:继分号建议更新的答案

这篇关于在获取node.js的二进制内容与http.request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆