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

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

问题描述

我想从 https 请求中检索二进制数据.

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

我发现了一个类似的问题,使用了请求方法,使用请求获取 Node.js 中的二进制内容,说将 encoding 设置为 null 应该可以,但它不会.

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);
    });
})

将编码设置为 'binary' 也不起作用

setting encoding to 'binary' doesn't work either

推荐答案

接受的答案对我不起作用(即,将编码设置为二进制),即使提出问题的用户提到它也不起作用.

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.

这对我有用,取自: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'));
    });
});

根据分号的建议更新答案

Update answer following a suggestion by Semicolon

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

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