UNPKG

2.82 kBTypeScriptView Raw
1/**
2 * The `string_decoder` module provides an API for decoding `Buffer` objects into
3 * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
4 * characters. It can be accessed using:
5 *
6 * ```js
7 * const { StringDecoder } = require('string_decoder');
8 * ```
9 *
10 * The following example shows the basic use of the `StringDecoder` class.
11 *
12 * ```js
13 * const { StringDecoder } = require('string_decoder');
14 * const decoder = new StringDecoder('utf8');
15 *
16 * const cent = Buffer.from([0xC2, 0xA2]);
17 * console.log(decoder.write(cent));
18 *
19 * const euro = Buffer.from([0xE2, 0x82, 0xAC]);
20 * console.log(decoder.write(euro));
21 * ```
22 *
23 * When a `Buffer` instance is written to the `StringDecoder` instance, an
24 * internal buffer is used to ensure that the decoded string does not contain
25 * any incomplete multibyte characters. These are held in the buffer until the
26 * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called.
27 *
28 * In the following example, the three UTF-8 encoded bytes of the European Euro
29 * symbol (`€`) are written over three separate operations:
30 *
31 * ```js
32 * const { StringDecoder } = require('string_decoder');
33 * const decoder = new StringDecoder('utf8');
34 *
35 * decoder.write(Buffer.from([0xE2]));
36 * decoder.write(Buffer.from([0x82]));
37 * console.log(decoder.end(Buffer.from([0xAC])));
38 * ```
39 * @see [source](https://github.com/nodejs/node/blob/v17.0.0/lib/string_decoder.js)
40 */
41declare module 'string_decoder' {
42 class StringDecoder {
43 constructor(encoding?: BufferEncoding);
44 /**
45 * Returns a decoded string, ensuring that any incomplete multibyte characters at
46 * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the
47 * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`.
48 * @since v0.1.99
49 * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.
50 */
51 write(buffer: Buffer): string;
52 /**
53 * Returns any remaining input stored in the internal buffer as a string. Bytes
54 * representing incomplete UTF-8 and UTF-16 characters will be replaced with
55 * substitution characters appropriate for the character encoding.
56 *
57 * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input.
58 * After `end()` is called, the `stringDecoder` object can be reused for new input.
59 * @since v0.9.3
60 * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.
61 */
62 end(buffer?: Buffer): string;
63 }
64}
65declare module 'node:string_decoder' {
66 export * from 'string_decoder';
67}