如何将二进制数据附加到 node.js 中的缓冲区 [英] How to append binary data to a buffer in node.js

查看:36
本文介绍了如何将二进制数据附加到 node.js 中的缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些二进制数据的缓冲区:

I have a buffer with some binary data:

var b = new Buffer ([0x00, 0x01, 0x02]);

我想附加 0x03.

如何附加更多的二进制数据?我在文档中搜索,但要附加数据,它必须是字符串,如果不是,则会发生错误(TypeError: Argument must be a string):

How can I append more binary data? I'm searching in the documentation but for appending data it must be a string, if not, an error occurs (TypeError: Argument must be a string):

var b = new Buffer (256);
b.write ("hola");
console.log (b.toString ("utf8", 0, 4)); //hola
b.write (", adios", 4);
console.log (b.toString ("utf8", 0, 11)); //hola, adios

然后,我在这里看到的唯一解决方案是为每个附加的二进制数据创建一个新缓冲区,并使用正确的偏移量将其复制到主缓冲区:

Then, the only solution I can see here is to create a new buffer for every appended binary data and copy it to the major buffer with the correct offset:

var b = new Buffer (4); //4 for having a nice printed buffer, but the size will be 16KB
new Buffer ([0x00, 0x01, 0x02]).copy (b);
console.log (b); //<Buffer 00 01 02 00>
new Buffer ([0x03]).copy (b, 3);
console.log (b); //<Buffer 00 01 02 03>

但这似乎有点低效,因为我必须为每个追加实例化一个新缓冲区.

But this seems a bit inefficient because I have to instantiate a new buffer for every append.

您知道附加二进制数据的更好方法吗?

Do you know a better way for appending binary data?

编辑

我编写了一个 BufferedWriter,它使用内部缓冲区将字节写入文件.与 BufferedReader 相同,但用于写入.

I've written a BufferedWriter that writes bytes to a file using internal buffers. Same as BufferedReader but for writing.

一个简单的例子:

//The BufferedWriter truncates the file because append == false
new BufferedWriter ("file")
    .on ("error", function (error){
        console.log (error);
    })

    //From the beginning of the file:
    .write ([0x00, 0x01, 0x02], 0, 3) //Writes 0x00, 0x01, 0x02
    .write (new Buffer ([0x03, 0x04]), 1, 1) //Writes 0x04
    .write (0x05) //Writes 0x05
    .close (); //Closes the writer. A flush is implicitly done.

//The BufferedWriter appends content to the end of the file because append == true
new BufferedWriter ("file", true)
    .on ("error", function (error){
        console.log (error);
    })

    //From the end of the file:
    .write (0xFF) //Writes 0xFF
    .close (); //Closes the writer. A flush is implicitly done.

//The file contains: 0x00, 0x01, 0x02, 0x04, 0x05, 0xFF

最后更新

使用 concat.

推荐答案

Node.js 的更新答案 ~>0.8

Node 现在能够自行连接缓冲区.

var newBuffer = Buffer.concat([buffer1, buffer2]);

Node.js ~0.6 的旧答案

我使用一个模块来添加一个 .concat 函数,其中包括:

https://github.com/coolaj86/node-bufferjs

我知道这不是一个纯粹的"解决方案,但它非常适合我的目的.

I know it isn't a "pure" solution, but it works very well for my purposes.

这篇关于如何将二进制数据附加到 node.js 中的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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