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

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

我发现一个类似的问题 ,使用请求方法, 获取二进制内容在Node.js使用请求 ,是说设置编码应该工作,但它不。

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

编辑:设置编码为“二进制”也不起作用

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

以下是我的工作,取自: 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')); }); }); 

编辑:根据分号build议更新答案

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

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

这里是有用的答案: 写图像到本地服务器