Module

std/node/buffer.ts>Buffer#copy

Deno standard library
Go to Latest
method Buffer.prototype.copy
import { Buffer } from "https://dotland.deno.dev/std@0.177.0/node/buffer.ts";

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

TypedArray.prototype.set() performs the same operation, and is available for all TypedArrays, including Node.js Buffers, although it takes different function arguments.

import { Buffer } from 'buffer';

// 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);
// This is equivalent to:
// buf2.set(buf1.subarray(16, 20), 8);

console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
import { Buffer } from 'buffer';

// 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

Parameters

target: Uint8Array

A Buffer or {@link Uint8Array} to copy into.

optional
targetStart: number

The offset within target at which to begin writing.

optional
sourceStart: number

The offset within buf from which to begin copying.

optional
sourceEnd: number

The offset within buf at which to stop copying (not inclusive).

Returns

number

The number of bytes copied.