从缓冲区中删除多个字节的规范方法

Canonical way to remove multiple bytes from buffer

假设我在 Node.js 中有一个简单的缓冲区,如下所示:

const bytes = Buffer.from('abcdefg');

这个缓冲区实例有 sliceconcat 作为方法,但我真的不确定如何使用它们来基本上创建数组的 pop/shift/splice 的功能。

这里是 Buffer 文档:https://nodejs.org/api/buffer.html

我基本上想要做的是 read/remove 第一个 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
}

这是我所拥有的,但对我来说它看起来很漂亮 "wrong",尽管它似乎也有效:

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() 方法的原因,因为它不是对本质上 fixed-size 不同于数组的东西的操作。 shiftsplice 也是如此。您不能扩展已分配的 Buffer,但可以创建新的。

使用 .slice() 不会给你一个新的 Buffer,而是 returns 原始 Buffer 占用的内存的一个子集。虽然这种方法有效,但可能有一些其他变量仍然引用原始 Buffer 的可能性,在这种情况下,对从 .slice() 获得的子集所做的修改可能会转移到原始 Buffer ] 还有。

鉴于 Buffer 的性质和您似乎想要的操作类型,最好先将 items 转换为字符串。然后,您可以通过使用 .split('') 进行拆分来执行您提到的所有操作。完成后,您可以加入拆分字符串并使用 Buffer.from(string) 创建一个新的 Buffer 并将其分配回 items。这样,你的代码会更清晰。