如何处理nodejs缓冲区(不确定长度)

时间:2015-04-11 06:34:02

标签: javascript node.js buffer

这是示例数据流(在缓冲区中)。 0x81是每个块的结尾,需要处理逻辑直到下一个0x81

  

00:15:04:00:00:30:04:54:52:55:45:05:14:00:00:00:04:4B:30:01:00:64:的 81 :00:14:04:00:00:10:03:42:57:47:03:0C:00:14:00:04:4B:31:01:01:F4: 81 :00:1A:04:00:00:14:07:44:43:4F:4E:2D:57:32:00:80:00:03:00:04:4B:33 :02:07:08:20:08:的 81 :00:15:04:00:00:20:04:49:52:50:43:01:BA:00:00: 00:04:4B:34:01:00:64:的 81 :00:15:04:00:00:00:04:42:44:4D:53:07:E4:00 :1E:00:04:4B:35:01:03:20:的 81

我需要处理完整的流,但不知道如何处理每个块的不确定长度。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用以下内容:

var bytes = "00:15:04:00:00:81:00:01:81:51:81".split(":");
var buffer = new Buffer(bytes);

function getNextBlock(buffer, pos) {
    if (pos >= buffer.length)
        return false;

    var block = [];
    while (pos < buffer.length && buffer[pos] != "81")
        block.push(buffer[pos++]);

    return block.length ? block : false;

}

var block;
var pos = 0;
while(block = getNextBlock(buffer, pos)) {
    console.log(block);
    pos += 1 + block.length;
}