使用http.request获取node.js中的二进制内容

edi*_*999 35 binary http node.js

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

我发现了一个类似的问题,使用请求方法,使用请求 获取Node.js中的二进制内容,是说将编码设置为null应该有效,但事实并非如此.

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);
    });
})
Run Code Online (Sandbox Code Playgroud)

编辑:将编码设置为'二进制'也不起作用

Gua*_*uru 65

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

这对我有用,取自: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'));
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑:按照Semicolon的建议更新答案


mok*_*oka 15

您需要将编码设置为响应,而不是请求:

req = https.request(options, function(res) {
    res.setEncoding('binary');

    var data = [ ];

    res.on('data', function(chunk) {
        data.push(chunk);
    });
    res.on('end', function() {
        var binary = Buffer.concat(data);
        // binary is your data
    });
    res.on('error', function(err) {
        console.log("Error during HTTP request");
        console.log(err.message);
    });
});
Run Code Online (Sandbox Code Playgroud)

这是一个有用的答案:将图像写入本地服务器

  • 这段代码说数据需要是一个缓冲区数组,但是有字符串( (3认同)

Pär*_*son 11

在AWS Lambda环境中运行NodeJS 6.10(和8.10,在2019年2月测试),对我来说,没有任何解决方案.

对我有用的是以下内容:

https.get(opt, (res) => {
    res.setEncoding('binary');
    let chunks = [];

    res.on('data', (chunk) => {
        chunks.push(Buffer.from(chunk, 'binary'));
    });

    res.on('end', () => {
        let binary = Buffer.concat(chunks);
        // binary is now a Buffer that can be used as Uint8Array or as
        // any other TypedArray for data processing in NodeJS or 
        // passed on via the Buffer to something else.
    });
});
Run Code Online (Sandbox Code Playgroud)

记下res.setEncoding('binary'); 和Buffer.from(chunk,'binary')行.一个设置响应编码,另一个从前面指定的编码中提供的字符串创建一个Buffer对象.


小智 8

  1. 不要调用setEncoding()方法,因为默认情况下不分配编码,流数据将作为Buffer对象返回
  2. 调用Buffer.from()回调on.data方法将值转换chunkBuffer对象。
http.get('my_url', (response) => {
  const chunks = [];
  response.on('data', chunk => chunks.push(Buffer.from(chunk))) // Converte `chunk` to a `Buffer` object.
    .on('end', () => {
      const buffer = Buffer.concat(chunks);
      console.log(buffer.toString('base64'));
    });
});
Run Code Online (Sandbox Code Playgroud)


小智 6

Pärt Johanson 我希望我能发表评论,感谢您将我从递归循环中拯救出来,我整天都在扯头发,然后一遍又一遍地阅读(非常无用的)节点文档。找到你的答案后,我去深入研究文档,我什至找不到res.setEncoding任何地方记录的方法!它只是作为两个示例的一部分显示,其中他们称res.setEncoding('utf8');您在哪里找到这个或您是如何弄清楚的!?

由于我没有足够的声誉来发表评论,我至少会为我的答案贡献一些有用的东西:Pärt Johanson 的答案对我来说是 100% 的,我只是根据我的需要稍微调整了它,因为我正在使用它来下载和使用nw.Window.get().evalNWBin()NWJS 0.36.4 / Node 11.11.0评估托管在我的服务器上的脚本(并使用 nwjc 编译):

let opt = {...};
let req = require('https').request(opt, (res) => {
  // server error returned
  if (200 !== res.statusCode) {
    res.setEncoding('utf8');
    let data = '';
    res.on('data', (strData) => {
      data += strData;
    });
    res.on('end', () => {
      if (!res.complete) {
        console.log('Server error, incomplete response: ' + data);
      } else {
        console.log('Server error, response: ' + data);
      }
    });
  }
  // expected response
  else {
    res.setEncoding('binary');
    let data = [];
    res.on('data', (binData) => {
      data.push(Buffer.from(binData, 'binary'));
    });
    res.on('end', () => {
      data = Buffer.concat(data);
      if (!res.complete) {
        console.log('Request completed, incomplete response, ' + data.length + ' bytes received');
      } else {
        console.log('Request completed, ' + data.length + ' bytes received');
        nw.Window.get().evalNWBin(null, data);
      }
    });
  }
};

Run Code Online (Sandbox Code Playgroud)

编辑:PS 我发布这个只是为了防止有人想知道如何处理非二进制响应——我的实际代码更深入一点并检查响应内容类型标头以解析 JSON(预期失败,即 400、401、403)或 HTML(意外失败,即 404 或 500)