在 NodeJS buf[index] 中,索引是缓冲区中的位置。它有助于在缓冲区中的索引位置设置或返回八位字节值。返回的值是介于 0x00 到 0xFF(十六进制)和 0 到 255(十进制)之间的单个字节。
如果为读取缓冲区中的值而给出的索引为负数或大于缓冲区长度,则返回的值是未定义的。如果索引为负数或大于缓冲区长度,它也不会更新 buffer 中的值。
语法
以下是NodeJS Buffer buf[index]属性的语法 -
Buf[index] = value
例
在此示例中,将创建一个缓冲区并读取位置 5 的值。
const buf = Buffer.from('Hello World');
console.log(buf);
console.log("The octet value at position 5 is :"+buf[5]);
输出
<Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
The octet value at position 5 is :32
The octet value at position 5 is :32
例
让我们使用大于 buffer.length 的索引。
const buf = Buffer.from('Hello World');
console.log(buf);
console.log("The octet value at position 15 is :"+buf[15]);
输出
<Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
The octet value at position 15 is :undefined
The octet value at position 15 is :undefined
例
在这个例子中,让我们在我们需要的位置更改八位字节值。
const buf = Buffer.from('Hello World');
buf[5] = 58;
console.log("The buffer after the octet value is changed at position 5 is :"+buf.toString());
输出
The buffer after the octet value is changed at position 5 is :Hello:World