假设我正在 Node.js 中构造一个可变长度的字符串或字节序列。 buf.write 的文档说:
https://nodejs.org/api/buffer.html#buffer_buf_write_string_offset_length_encoding
Writes string to buf at offset according to the character encoding in encoding. The length parameter is the number of bytes to write. If buf did not contain enough space to fit the entire string, only a partial amount of string will be written. However, partially encoded characters will not be written.
假设我想写入比缓冲区空间更多的数据。推荐的种植方式是什么?似乎没有 .grow
方法或类似方法。我可以调用 Buffer.from(buf)
来创建一个新的 Buffer,但这似乎效率不高。
最佳答案
如果你在每次添加后不需要整个缓冲区的所有内容,我认为你可以在这里使用一个 block (缓冲区)数组和 Buffer.concat(chunks)
来构建必要时整个缓冲区。
const chunks = [];
chunks.push(Buffer.from([0xE2, 0xAD, 0x90])); // star
chunks.push(Buffer.from([0xF0, 0x9F, 0x9A, 0x80])); // rocket
const buf = Buffer.concat(chunks);
console.log(buf.toString());
关于javascript - 增加缓冲区的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898229/