字串解碼器#

穩定性:2 - 穩定

原始碼: lib/string_decoder.js

node:string_decoder 模組提供了一個 API,用於將 Buffer 物件解碼為字串,並保留編碼後的多位元組 UTF-8 和 UTF-16 字元。可以使用以下方式訪問它:

import { StringDecoder } from 'node:string_decoder';const { StringDecoder } = require('node:string_decoder');

以下示例展示了 StringDecoder 類的基本用法。

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: €const { StringDecoder } = require('node:string_decoder');
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: €

當一個 Buffer 例項被寫入 StringDecoder 例項時,會使用一個內部緩衝區來確保解碼後的字串不包含任何不完整的多位元組字元。這些字元會被保留在緩衝區中,直到下一次呼叫 stringDecoder.write()stringDecoder.end()

在下面的示例中,歐元符號()的三個 UTF-8 編碼位元組透過三個獨立的操作寫入:

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: €const { StringDecoder } = require('node:string_decoder');
const decoder = new StringDecoder('utf8');

decoder.write(Buffer.from([0xE2]));
decoder.write(Buffer.from([0x82]));
console.log(decoder.end(Buffer.from([0xAC]))); // Prints: €

類: StringDecoder#

new StringDecoder([encoding])#

  • encoding <string> StringDecoder 將使用的字元編碼預設值: 'utf8'

建立一個新的 StringDecoder 例項。

stringDecoder.end([buffer])#

將內部緩衝區中儲存的任何剩餘輸入作為字串返回。代表不完整 UTF-8 和 UTF-16 字元的位元組將被替換為適合該字元編碼的替換字元。

如果提供了 buffer 引數,在返回剩餘輸入之前,會最後再執行一次對 stringDecoder.write() 的呼叫。呼叫 end() 之後,stringDecoder 物件可以被重用於處理新的輸入。

stringDecoder.write(buffer)#

返回一個解碼後的字串,並確保 BufferTypedArrayDataView 末尾的任何不完整的多位元組字元從返回的字串中省略,並存儲在內部緩衝區中,以供下一次呼叫 stringDecoder.write()stringDecoder.end() 時使用。