在Node.js中使用本机http.get()
,我正在尝试将HTTP响应传递给我可以将data
和end
事件绑定到的流。
我正在使用以下方法处理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压缩的内容,是否有任何复制此同一笔交易的建议?
答案 0 :(得分:22)
来自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
});
});
如果上面示例中的readable.pipe(dest)
是可写流,body
基本上会做同样的事情。
答案 1 :(得分:3)
如今,建议的管道布置方式是使用管道功能。它应该可以防止内存泄漏。
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));