buf.subarray([start[, end]])


  • start <integer> 新的 Buffer 将从此处开始。默认值: 0
  • end <integer> 新的 Buffer 将在此结束(不包括在内)。默认值: buf.length
  • 返回:<Buffer>

返回一个新的 Buffer,它引用与原始缓冲区相同的内存,但通过 startend 索引进行了偏移和裁剪。

🌐 Returns a new Buffer that references the same memory as the original, but offset and cropped by the start and end indexes.

指定 end 大于 buf.length 将返回与 end 等于 buf.length 相同的结果。

🌐 Specifying end greater than buf.length will return the same result as that of end equal to buf.length.

此方法继承自 TypedArray.prototype.subarray()

🌐 This method is inherited from TypedArray.prototype.subarray().

修改新的 Buffer 切片会修改原始 Buffer 中的内存,因为两个对象分配的内存是重叠的。

🌐 Modifying the new Buffer slice will modify the memory in the original Buffer because the allocated memory of the two objects overlap.

import { Buffer } from 'node:buffer';

// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

const buf2 = buf1.subarray(0, 3);

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc

buf1[0] = 33;

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bcconst { Buffer } = require('node:buffer');

// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

const buf2 = buf1.subarray(0, 3);

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc

buf1[0] = 33;

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bc

指定负索引会导致切片相对于 buf 的末尾而不是开头生成。

🌐 Specifying negative indexes causes the slice to be generated relative to the end of buf rather than the beginning.

import { Buffer } from 'node:buffer';

const buf = Buffer.from('buffer');

console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)

console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)

console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)const { Buffer } = require('node:buffer');

const buf = Buffer.from('buffer');

console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)

console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)

console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)