假设我在 Node.js 中有一个简单的缓冲区,如下所示:
const bytes = Buffer.from('abcdefg');
这个缓冲区实例有 slice
和 concat
作为方法,但我真的不确定如何使用它们来基本上创建一个 pop/shift/splice 的功能数组。
这里是缓冲区文档:https://nodejs.org/api/buffer.html
我基本上想要做的是读取/删除前 X 个字节,如下所示:
function read(x){
// return the first x number of bytes from buffer
// and remove those bytes from the buffer
// side-effects be damned for the moment
}
这是我所拥有的,但对我来说它似乎很“错误”,尽管它似乎也有效:
let items = Buffer.from('abcdefg');
function read(x){
const b = items.slice(0,x);
items = items.slice(x,items.length);
return b;
}
console.log(String(read(4)));
console.log(String(items));
有更好的方法吗?
另外,我不确定 read 是否是正确的词,但 pop 表示数组...使用什么词来描述此函数的作用是正确的?
最佳答案
来自Node.js API :
Instances of the Buffer class are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the V8 heap. The size of the Buffer is established when it is created and cannot be resized.
这就是为什么 Buffer
没有 .pop()
方法的原因,因为与数组不同,它不是针对本质上固定大小的对象的操作。 shift
和 splice
也是如此。您不能扩展已分配的 Buffer
,但可以创建新的。
使用.slice()
不会给你一个新的Buffer
,而是返回原始Buffer
占用的内存的一个子集>。虽然这种方法有效,但可能有一些其他变量仍然引用原始 Buffer
的可能性,在这种情况下,对从 .slice()
获得的子集进行的修改可能也转移到原始的 Buffer
。
鉴于 Buffer
的性质和您似乎想要的操作类型,最好先将 items
转换为字符串。然后,您可以通过使用 .split('')
进行拆分来执行您提到的所有操作。完成后,您可以加入拆分字符串并使用 Buffer.from(string)
创建一个新的 Buffer
并将其分配回 items
。这样,您的代码将更加清晰。
关于javascript - 从缓冲区中删除多个字节的规范方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41668445/