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

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

我想追加0x03个.

如何添加更多二进制数据?我正在文档中搜索,但对于附加数据,它必须是字符串,如果不是,则会发生错误(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

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

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>

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

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

EDIT

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

举个简单的例子:

//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

LAST UPDATE

使用concat.

推荐答案

更新了 node 的答案.js~>0.8

Node现在可以独立运行concatenate buffers次.

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

node 的旧答案.js~0.6

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

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

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

Node.js相关问答推荐

使用Moongose处理node.js中重定向的then()块链

在我的Next.js应用程序中没有正确设置Process.env.NODE_ENV

如何在Node.js 中设置图表js的背景色

已知NPM无法在node.js V12上运行的问题

无法使用Sequelize连接AWS RDS

一个函数中的两个依赖的NodeJS数据库操作.如果第二个失败了怎么办?

Axios TypeError:将循环 struct 转换为 JSON

Mongodb - 在数组数组中查找()

Mocha调用所有it回调模拟(测试中间件)

带有事件网格的 Azure 函数在没有 ngrok 的情况下在本地运行

'{ id: string; 类型的参数}' 不可分配给FindOneOptions类型的参数

2 x 匹配标准显示没有结果

即使部署成功,也不会触发 Firebase 函数来填充 Firestore 集合.为什么?

node_modules 中 .bin 文件夹的用途是什么?

如何在 MongoDB collection.find() 上获取回调

Node_redis - 如何删除密钥?

在 Node.js 与 Cron 作业(job)中设置间隔?

Selenium WebDriver 等到元素显示

Node.js 中的 PHP exit()/die() 类似功能是什么

桌面应用程序仅支持 oauth_callback 值 'oob'/oauth/request_token