buf.subarray([start[, end]])
-
start<integer> 新的Buffer将开始的位置。默认值:0。¥
start<integer> Where the newBufferwill start. Default:0. -
end<integer> 新的Buffer将结束的位置(不包括在内)。默认值:buf.length。¥
end<integer> Where the newBufferwill end (not inclusive). Default:buf.length. -
返回:<Buffer>
¥Returns: <Buffer>
返回一个新的 Buffer,它引用与原始内存相同的内存,但由 start 和 end 索引进行偏移和裁剪。
¥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).)