buf[index]


索引操作符 [index] 可用于获取或设置 buf 中指定位置的字节。 该值指向单个字节,所以有效的值的范围是 0x000xFF(十六进制),或 0255(十进制)。

该操作符继承自 Uint8Array,所以对越界访问的处理与 UInt8Array 相同(取值时返回 undefined,赋值时不作为)。

// 拷贝 ASCII 字符串到 `Buffer`,每次拷贝一个字节。

const str = 'http://nodejs.cn/';
const buf = Buffer.allocUnsafe(str.length);

for (let i = 0; i < str.length; i++) {
  buf[i] = str.charCodeAt(i);
}

console.log(buf.toString('ascii'));
// 打印: http://nodejs.cn/

The index operator [index] can be used to get and set the octet at position index in buf. The values refer to individual bytes, so the legal value range is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).

This operator is inherited from Uint8Array, so its behavior on out-of-bounds access is the same as UInt8Array - that is, getting returns undefined and setting does nothing.

// Copy an ASCII string into a `Buffer` one byte at a time.

const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);

for (let i = 0; i < str.length; i++) {
  buf[i] = str.charCodeAt(i);
}

console.log(buf.toString('ascii'));
// Prints: Node.js