Node.js v25.0.0 文件
- Node.js v25.0.0
- 目錄
-
索引
- 斷言測試
- 非同步上下文跟蹤
- 非同步鉤子
- 緩衝區
- C++ 外掛
- 使用 Node-API 的 C/C++ 外掛
- C++ 嵌入器 API
- 子程序
- 叢集
- 命令列選項
- 控制檯
- 加密
- 偵錯程式
- 已棄用的 API
- 診斷通道
- DNS
- 域
- 環境變數
- 錯誤
- 事件
- 檔案系統
- 全域性物件
- HTTP
- HTTP/2
- HTTPS
- 檢查器
- 國際化
- 模組:CommonJS 模組
- 模組:ECMAScript 模組
- 模組:
node:moduleAPI - 模組:包
- 模組:TypeScript
- 網路
- 作業系統
- 路徑
- 效能鉤子
- 許可權
- 程序
- Punycode
- 查詢字串
- 逐行讀取
- REPL
- 報告
- 單一可執行檔案應用
- SQLite
- 流
- 字串解碼器
- 測試執行器
- 定時器
- TLS/SSL
- 跟蹤事件
- TTY
- UDP/資料報
- URL
- 實用工具
- V8
- 虛擬機器
- WASI
- Web Crypto API
- Web Streams API
- 工作執行緒
- Zlib
- 其他版本
- 選項
字串解碼器#
穩定性:2 - 穩定
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])#
建立一個新的 StringDecoder 例項。
stringDecoder.end([buffer])#
buffer<string> | <Buffer> | <TypedArray> | <DataView> 要解碼的位元組。- 返回: <string>
將內部緩衝區中儲存的任何剩餘輸入作為字串返回。代表不完整 UTF-8 和 UTF-16 字元的位元組將被替換為適合該字元編碼的替換字元。
如果提供了 buffer 引數,在返回剩餘輸入之前,會最後再執行一次對 stringDecoder.write() 的呼叫。呼叫 end() 之後,stringDecoder 物件可以被重用於處理新的輸入。
stringDecoder.write(buffer)#
buffer<string> | <Buffer> | <TypedArray> | <DataView> 要解碼的位元組。- 返回: <string>
返回一個解碼後的字串,並確保 Buffer、TypedArray 或 DataView 末尾的任何不完整的多位元組字元從返回的字串中省略,並存儲在內部緩衝區中,以供下一次呼叫 stringDecoder.write() 或 stringDecoder.end() 時使用。