From 9b2f1e73cee0b50d3b0f2d5845a49e8f1f515284 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sat, 4 Feb 2023 14:02:10 -0800 Subject: [PATCH] buffer: add Buffer.copyFrom(...) Fixes: https://github.com/nodejs/node/issues/43862 --- doc/api/buffer.md | 21 +++++++++++++ lib/buffer.js | 50 +++++++++++++++++++++++++++++++ test/parallel/test-buffer-from.js | 45 +++++++++++++++++++++++++++- 3 files changed, 115 insertions(+), 1 deletion(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 5c8b661e76e9cd..524ee1394efedc 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1058,6 +1058,27 @@ console.log(bufA.length); `Buffer.concat()` may also use the internal `Buffer` pool like [`Buffer.allocUnsafe()`][] does. +### Static method: `Buffer.copyFrom(view[, offset[, length]])` + + + +* `view` {TypedArray|DataView} The {TypedArray} or {DataView} to copy +* `offset` {integer} The starting offset within `view` +* `length` {integer} The number of elements from `view` to copy. + +Copies the underlying memory of `view` into a new `Buffer`. + +```js +const u16 = new Uint16Array([0, 0xffff]); +const buf = Buffer.copyFrom(u16, 0, 1); +u16[1] = 0; +console.log(buf.length); // 2 +console.log(buf[0]); // 255 +console.log(buf[1]); // 255 +``` + ### Static method: `Buffer.from(array)`