buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])


  • target <Buffer> | <Uint8Array> 要拷贝进的 BufferUint8Array
  • targetStart <integer> target 中开始写入的偏移量。默认值: 0
  • sourceStart <integer> buf 中开始拷贝的偏移量。默认值: 0
  • sourceEnd <integer> buf 中结束拷贝的偏移量(不包含)。默认值: buf.length
  • 返回: <integer> 拷贝的字节数。

拷贝 buf 中某个区域的数据到 target 中的某个区域,即使 target 的内存区域与 buf 的重叠。

// 创建两个 `Buffer`。
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');

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

// 拷贝 `buf1` 中第 16 至 19 字节偏移量的数据到 `buf2` 第 8 字节偏移量开始。
buf1.copy(buf2, 8, 16, 20);

console.log(buf2.toString('ascii', 0, 25));
// 打印: !!!!!!!!qrst!!!!!!!!!!!!!
// 创建一个 `Buffer`,并拷贝同一 `Buffer` 中一个区域的数据到另一个重叠的区域。

const buf = Buffer.allocUnsafe(26);

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

buf.copy(buf, 0, 4, 10);

console.log(buf.toString());
// 打印: efghijghijklmnopqrstuvwxyz
  • target <Buffer> | <Uint8Array> A Buffer or Uint8Array to copy into.
  • targetStart <integer> The offset within target at which to begin writing. Default: 0.
  • sourceStart <integer> The offset within buf from which to begin copying. Default: 0.
  • sourceEnd <integer> The offset within buf at which to stop copying (not inclusive). Default: buf.length.
  • Returns: <integer> The number of bytes copied.

Copies data from a region of buf to a region in target even if the target memory region overlaps with buf.

// Create two `Buffer` instances.
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');

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

// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`
buf1.copy(buf2, 8, 16, 20);

console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
// Create a `Buffer` and copy data from one region to an overlapping region
// within the same `Buffer`.

const buf = Buffer.allocUnsafe(26);

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

buf.copy(buf, 0, 4, 10);

console.log(buf.toString());
// Prints: efghijghijklmnopqrstuvwxyz