1. 程式人生 > 程式設計 >Node.js API詳解之 string_decoder用法例項分析

Node.js API詳解之 string_decoder用法例項分析

本文例項講述了Node.js API詳解之 string_decoder用法。分享給大家供大家參考,具體如下:

string_decoder 模組提供了一個 API,用於把 Buffer 物件解碼成字串。

對於引數末尾不完整的多位元組字元,string_decoder會將其儲存在內部的buffer中,當再次解碼時,補充到引數開頭。

通過 const { StringDecoder } = require(‘string_decoder'); 的方式引用string_decoder模組。

目錄:

  • new StringDecoder([encoding])
  • stringDecoder.write(buffer)
  • stringDecoder.end([buffer])

new StringDecoder([encoding])

說明:

建立一個新的StringDecoder例項,可傳遞encoding引數作為字元編碼格式,預設為'utf8′

stringDecoder.write(buffer)

說明:

返回一個解碼後的字串,並確保返回的字串不包含殘缺的多位元組字元,殘缺的多位元組字元會被儲存在一個內部的 buffer 中,
用於下次呼叫 stringDecoder.write() 或 stringDecoder.end()。
buffer:待解碼的Buffer

demo:

const decoder = new StringDecoder('utf8');
 
//字元的16進位制小於0x80屬於單位元組
let outString = decoder.write(Buffer.from([0x78,0x69,0x61,0x6f,0x71,0x6e,0x67]));
 
console.log(outString);
//xiaoqiang
 
//字元的16進位制大於0x80屬於雙位元組
outString = decoder.write(Buffer.from([0xC2,0xA2]));
 
console.log(outString);
//¢
 
//單雙位元組混合,置於末尾
outString = decoder.write(Buffer.from([0x78,0x67,0xC2]));
 
console.log(outString);
//xiaoqiang
 
outString = decoder.write(Buffer.from([0xA2]));
 
console.log(outString);
//¢
 
//單雙位元組混合,置於中間
outString = decoder.write(Buffer.from([0x78,0xC2,0x67]));
 
console.log(outString);
//xiaoq?iang
 
outString = decoder.write(Buffer.from([0xA2]));
 
console.log(outString);
//?
 
//單雙位元組混合,置於開始
outString = decoder.write(Buffer.from([0xC2,0x78,0x67]));
 
console.log(outString);
//?xiaoqiang
 
outString = decoder.write(Buffer.from([0xA2]));
 
console.log(outString);
//?
 
//單雙位元組混合,置於末尾
outString = decoder.write(Buffer.from([0x78,0xC2]));
 
console.log(outString);
//xiaoqiang
 
outString = decoder.write(Buffer.from([0x78,0xA2]));
 
console.log(outString);
//?x?

stringDecoder.end([buffer])

說明:

以字串的形式返回內部 buffer 中剩餘的位元組,殘缺的位元組會被替換成符合字元編碼的字元
如果提供了 buffer 引數,則在返回剩餘位元組之前會再執行一次 stringDecoder.write()

demo:

const decoder = new StringDecoder('utf8');
 
//字元的16進位制小於0x80屬於單位元組
let outString = decoder.write(Buffer.from([0x78,0x67]));
 
console.log(outString);
//xiaoqiang
 
outString = decoder.end();
 
console.log(outString);
//
 
//單雙位元組混合,置於末尾
outString = decoder.write(Buffer.from([0x78,0xC2]));
 
console.log(outString);
//xiaoqiang
 
outString = decoder.end(Buffer.from([0xA2]));
 
console.log(outString);
//¢
 
//單雙位元組混合,置於末尾
outString = decoder.write(Buffer.from([0x78,0xC2]));
 
console.log(outString);
//xiaoqiang
 
outString = decoder.end();
 
console.log(outString);
//?

希望本文所述對大家node.js程式設計有所幫助。