From 51eb4c0cdaf6257af4302e321dec2dd9cf28c5cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alfredo=20Gonz=C3=A1lez?= <12631491+mfdebian@users.noreply.github.com> Date: Sat, 26 Oct 2024 17:36:25 -0300 Subject: [PATCH] doc: add esm examples to node:string_decoder PR-URL: https://github.com/nodejs/node/pull/55507 Reviewed-By: Luigi Pinca Reviewed-By: Chemi Atlow --- doc/api/string_decoder.md | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/doc/api/string_decoder.md b/doc/api/string_decoder.md index 18960f6acb1736..5d848cfb6d550b 100644 --- a/doc/api/string_decoder.md +++ b/doc/api/string_decoder.md @@ -10,13 +10,29 @@ The `node:string_decoder` module provides an API for decoding `Buffer` objects into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 characters. It can be accessed using: -```js +```mjs +import { StringDecoder } from 'node:string_decoder'; +``` + +```cjs const { StringDecoder } = require('node:string_decoder'); ``` The following example shows the basic use of the `StringDecoder` class. -```js +```mjs +import { StringDecoder } from 'node:string_decoder'; +import { Buffer } from 'node:buffer'; +const decoder = new StringDecoder('utf8'); + +const cent = Buffer.from([0xC2, 0xA2]); +console.log(decoder.write(cent)); // Prints: ¢ + +const euro = Buffer.from([0xE2, 0x82, 0xAC]); +console.log(decoder.write(euro)); // Prints: € +``` + +```cjs const { StringDecoder } = require('node:string_decoder'); const decoder = new StringDecoder('utf8'); @@ -35,7 +51,17 @@ next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. In the following example, the three UTF-8 encoded bytes of the European Euro symbol (`€`) are written over three separate operations: -```js +```mjs +import { StringDecoder } from 'node:string_decoder'; +import { Buffer } from 'node:buffer'; +const decoder = new StringDecoder('utf8'); + +decoder.write(Buffer.from([0xE2])); +decoder.write(Buffer.from([0x82])); +console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € +``` + +```cjs const { StringDecoder } = require('node:string_decoder'); const decoder = new StringDecoder('utf8');