如何在 Node.js 中“累积"原始流? [英] How can I 'accumulate' a raw stream in Node.js?

查看:46
本文介绍了如何在 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?

推荐答案

首先,检查这些函数实际上是否需要一次性全部字节.他们真的应该接受 'data' 事件,这样你就可以按照接收它们的顺序传递缓冲区.

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.

无论如何,这是一种无需解码即可连接所有数据块缓冲区的蛮力方法:

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

这篇关于如何在 Node.js 中“累积"原始流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆