问题描述
最后更新
使用concat.
修改
我写了一个写入字节使用内部缓冲区中的文件。同但对于写作。
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
原题
我有一些二进制数据的缓冲区:
I have a buffer with some binary data:
var b = new Buffer ([0x00, 0x01, 0x02]);
我要追加 0×03
。
我怎么能追加更多的二进制数据?我在寻找的文档中,但对于追加的数据必须是一个字符串,如果没有,发生错误(类型错误:参数必须是一个字符串的):
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?
对不起我的英文不好。
推荐答案
节点能够concatenate缓冲区对自己现在的。
var newBuffer = Buffer.concat([buffer1, buffer2]);
旧的答案的Node.js〜0.6
我用一个模块来添加一个 .concat
功能,其中包括:
我知道这是不是一个纯粹的解决方案,但它工作得很好,我的目的。
I know it isn't a "pure" solution, but it works very well for my purposes.
这篇关于如何二进制数据追加到node.js的一个缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!