【问题标题】:Node.js HTTP response streamsNode.js HTTP 响应流
【发布时间】:2013-11-04 00:12:43
【问题描述】:

使用 Node.js 中的原生 http.get(),我试图将 HTTP 响应通过管道传输到我可以将 dataend 事件绑定到的流。

我目前正在处理 gzip 数据,使用:

http.get(url, function(res) {
  if (res.headers['content-encoding'] == 'gzip') {
    res.pipe(gunzip);
    gunzip.on('data', dataCallback);
    gunzip.on('end', endCallback);
  }
});

Gunzip 是一个流,这很有效。我尝试创建流(写入流,然后读取流)并通过管道传输响应,但运气不佳。对于非 gzip 压缩的内容,有什么建议可以复制同样的交易?

【问题讨论】:

  • 我正在尝试获取响应正文,然后在完成后获取。我以为我可以做到res.on('data'),但这似乎永远不会触发。

标签: javascript node.js gzip


【解决方案1】:

来自 HTTP 请求的响应对象是可读流的实例。因此,您将使用data 事件收集数据,然后在end 事件触发时使用它。

var http = require('http');
var body = '';

http.get(url, function(res) {
  res.on('data', function(chunk) {
    body += chunk;
  });
  res.on('end', function() {
    // all data has been downloaded
  });
});

如果上面示例中的body 是可写流,readable.pipe(dest) 基本上会做同样的事情。

【讨论】:

  • Doh,原来是由于 http 没有遵循重定向。你的代码就是我所拥有的,它工作正常,除了重定向。我检查了 npm follow-redirects 并将对其进行测试。
  • 你也可以试试流行的request 模块,它也遵循重定向
  • @vkurchatkin request 确实支持压缩内容
  • 为什么要进行字符串连接?块不是数据的全部吗?
  • 您需要进行字符串连接,因为响应是一个流。 data 事件在数据立即可用时触发,这可能是也可能不是整个响应。
【解决方案2】:

现在推荐的管道方式是使用管道功能。它应该可以保护您免受内存泄漏。

const { createReadStream} = require('fs');
const { pipeline } = require('stream')
const { createServer, get } = require('http')

const errorHandler = (err) => err && console.log(err.message);

const server = createServer((_, response) => {
  pipeline(createReadStream(__filename), response, errorHandler)
  response.writeHead(200);
}).listen(8080);

get('http://localhost:8080', (response) => {
  pipeline(response, process.stdout, errorHandler);
  response.on('close', () => server.close())
});

另一种具有更多控制权的方法是使用异步迭代器

async function handler(response){
  let body = ''
  for await (const chunk of response) {
    let text = chunk.toString()
    console.log(text)
    body += text
  }
  console.log(body.length)
  server.close()
}

get('http://localhost:8080', (response) => handler(response).catch(console.warn));

【讨论】:

    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2017-09-24
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多