[英]How can I 'accumulate' a raw stream in Node.js?
At the moment I concatenate everything into a string as follows 目前我将所有内容连接成一个字符串,如下所示
var body = '';
res.on('data', function(chunk){
body += chunk;
});
How can I preserve and accumulate the raw stream so I can pass raw bytes to functions that are expecting bytes and not String? 如何保存和累积原始流,以便将原始字节传递给期望字节而不是字符串的函数?
Better use Buffer.concat - much simpler. 更好地使用Buffer.concat - 更简单。 Available in Node v0.8+.
可在Node v0.8 +中使用。
var chunks = [];
res.on('data', function(chunk) { chunks.push(chunk); });
res.on('end', function() {
var body = Buffer.concat(chunks);
// Do work with body.
});
First off, check that these functions actually need the bytes all in one go. 首先,检查这些函数是否真的需要一次性完成所有字节。 They really should accept
'data'
events so that you can just pass on the buffers in the order you receive them. 他们真的应该接受
'data'
事件,这样你就可以按照收到它们的顺序传递缓冲区。
Anyway, here's a bruteforce way to concatenate all data chunk buffers without decoding them: 无论如何,这是一种连接所有数据块缓冲区而不解码它们的强力方法:
var bodyparts = [];
var bodylength = 0;
res.on('data', function(chunk){
bodyparts.push(chunk);
bodylength += chunk.length;
});
res.on('end', function(){
var body = new Buffer(bodylength);
var bodyPos=0;
for (var i=0; i < bodyparts.length; i++) {
bodyparts[i].copy(body, bodyPos, 0, bodyparts[i].length);
bodyPos += bodyparts[i].length;
}
doStuffWith(body); // yay
});
Alternately, you can also use a node.js library like bl or concat-stream: 或者,您也可以使用像bl或concat-stream这样的node.js库:
'use strict'
let http = require('http')
let bl = require('bl')
http.get(url, function (response) {
response.pipe(bl(function (err, data) {
if (err)
return console.error(err)
console.log(data)
}))
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.