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


创建一个指向与原始 Buffer 同一内存的新 Buffer,但使用 startend 进行了裁剪。

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

// 创建一个包含 ASCII 字母表的 `Buffer`,然后进行切片,再修改原始 `Buffer` 上的一个字节。

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i < 26; i++) {
  // 97 是 'a' 的十进制 ASCII 值。
  buf1[i] = i + 97;
}

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

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

buf1[0] = 33;

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

如果指定负的偏移量,则切片的生成是相对于 buf 的末尾而不是开头。

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

console.log(buf.slice(-6, -1).toString());
// 打印: buffe(相当于 buf.slice(0, 5))

console.log(buf.slice(-6, -2).toString());
// 打印: buff(相当于 buf.slice(0, 4))

console.log(buf.slice(-5, -2).toString());
// 打印: uff(相当于 buf.slice(1, 4))

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

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

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

// 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.slice(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

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

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

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

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

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