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

标签 javascript node.js buffer node.js-buffer

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

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

这个缓冲区实例有 sliceconcat 作为方法,但我真的不确定如何使用它们来基本上创建一个 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() 方法的原因,因为与数组不同,它不是针对本质上固定大小的对象的操作。 shiftsplice 也是如此。您不能扩展已分配的 Buffer,但可以创建新的。

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

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

关于javascript - 从缓冲区中删除多个字节的规范方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41668445/

相关文章:

c++ - 二进制 * 的无效操作数

javascript - CRM 2011 - 选项集上的简单 Javascript 确认框

javascript - onMouseMove + onMouseDown 调用函数

javascript - 将输入文本与字符串数组进行比较后,突出显示结果中的匹配词

node.js - Loopback API Explorer 身份验证

node.js - 在 NodeJS localhost 中设置时区以反射(reflect)生产环境

javascript - 如何将一个 <div> 置于其他几个 <div> 的中心(混合使用 w3.css 和 css)

node.js - 如何让 window.onload 函数在 Jade 模板语言中工作

c - 在 C 语言的循环中重复在堆栈上创建缓冲区是不好的做法吗?

c - 双链表不能正常工作,C