From 569de2553ecc59cdcb2543cb4b195c3bdfb5e06d Mon Sep 17 00:00:00 2001 From: Yagiz Nizipli Date: Thu, 10 Nov 2022 09:56:29 -0500 Subject: [PATCH] buffer: add asString static method --- doc/api/buffer.md | 37 +++++++++++++++++++ lib/buffer.js | 11 ++++++ src/node_buffer.cc | 32 +++++++++++++++++ test/parallel/test-buffer-asstring.js | 52 +++++++++++++++++++++++++++ 4 files changed, 132 insertions(+) create mode 100644 test/parallel/test-buffer-asstring.js diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 8b46553ec4941a..9bf4e57038b1ba 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -888,6 +888,43 @@ socket.on('readable', () => { A `TypeError` will be thrown if `size` is not a number. +### Static method: `Buffer.asString(list[, encoding])` + + + +* `list` {ArrayBufferView|ArrayBuffer|SharedArrayBuffer} Resource +* `encoding` {string} If `string` is a string, this is its encoding. + **Default** `'utf8'` +* Returns: {string} The encoded string representation of `list` + +```mjs +import { Buffer } from 'node:buffer'; + +const buf = new Uint8Array([ + 104, 101, 108, 108, + 111, 32, 119, 111, + 114, 108, 100, +]); + +console.log(Buffer.asString(buf)); +// Prints: 'hello world' +``` + +```cjs +const { Buffer } = require('node:buffer'); + +const buf = new Uint8Array([ + 104, 101, 108, 108, + 111, 32, 119, 111, + 114, 108, 100, +]); + +console.log(Buffer.asString(buf)); +// Prints: 'hello world' +``` + ### Static method: `Buffer.byteLength(string[, encoding])`