From 9fd831b8c9213424e405607dd7e581849cd85c3a Mon Sep 17 00:00:00 2001 From: Marco Ippolito Date: Mon, 12 Dec 2022 10:25:06 +0100 Subject: [PATCH] doc: buffer.fill empty value PR-URL: https://github.com/nodejs/node/pull/45794 Fixes: https://github.com/nodejs/node/issues/45727 Reviewed-By: Yagiz Nizipli Reviewed-By: Paolo Insogna --- doc/api/buffer.md | 13 +++++++++++++ test/parallel/test-buffer-fill.js | 15 +++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index f3d301951f7e3d..e4d9c0968d89e1 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -1882,6 +1882,7 @@ changes: --> * `value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`. + Empty value (string, Uint8Array, Buffer) is coerced to `0`. * `offset` {integer} Number of bytes to skip before starting to fill `buf`. **Default:** `0`. * `end` {integer} Where to stop filling `buf` (not inclusive). **Default:** @@ -1902,6 +1903,12 @@ const b = Buffer.allocUnsafe(50).fill('h'); console.log(b.toString()); // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + +// Fill a buffer with empty string +const c = Buffer.allocUnsafe(5).fill(''); + +console.log(c.fill('')); +// Prints: ``` ```cjs @@ -1913,6 +1920,12 @@ const b = Buffer.allocUnsafe(50).fill('h'); console.log(b.toString()); // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + +// Fill a buffer with empty string +const c = Buffer.allocUnsafe(5).fill(''); + +console.log(c.fill('')); +// Prints: ``` `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index e91492a59e81b3..c3476461fdaf8f 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -429,3 +429,18 @@ assert.throws(() => { code: 'ERR_INVALID_ARG_VALUE', name: 'TypeError' }); + + +{ + const bufEmptyString = Buffer.alloc(5, ''); + assert.strictEqual(bufEmptyString.toString(), '\x00\x00\x00\x00\x00'); + + const bufEmptyArray = Buffer.alloc(5, []); + assert.strictEqual(bufEmptyArray.toString(), '\x00\x00\x00\x00\x00'); + + const bufEmptyBuffer = Buffer.alloc(5, Buffer.alloc(5)); + assert.strictEqual(bufEmptyBuffer.toString(), '\x00\x00\x00\x00\x00'); + + const bufZero = Buffer.alloc(5, 0); + assert.strictEqual(bufZero.toString(), '\x00\x00\x00\x00\x00'); +}