• Node.js Video Tutorials

Node.js - Buffer.buf[index] 屬性



在 NodeJS 中,buf[index] 中的 index 是緩衝區中的一個位置。它用於設定或返回緩衝區中 index 位置處的八位位元組值。返回的值是單個位元組,範圍在 0x00 到 0xFF(十六進位制)和 0 到 255(十進位制)之間。

如果提供的 index 用於讀取緩衝區中的值,且 index 為負數或大於緩衝區長度,則返回的值為 undefined。如果 index 為負數或大於緩衝區長度,它也不會更新緩衝區中的值。

語法

以下是 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

示例

讓我們使用大於 buffer.length 的 index。

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

示例

在本例中,讓我們更改所需位置處的八位位元組值。

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
nodejs_buffer_module.htm
廣告