您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了Node.js API中怎么使用string_decoder,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
string_decoder 模塊提供了一個 API,用于把 Buffer 對象解碼成字符串。
對于參數末尾不完整的多字節字符,string_decoder會將其保存在內部的buffer中,當再次解碼時,補充到參數開頭。
通過 const { StringDecoder } = require(‘string_decoder'); 的方式引用string_decoder模塊。
目錄:
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, 0x69, 0x61, 0x6e, 0x67])); console.log(outString); //xiaoqiang //字符的16進制大于0x80屬于雙字節 outString = decoder.write(Buffer.from([0xC2, 0xA2])); console.log(outString); //¢ //單雙字節混合,置于末尾 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 0xC2])); console.log(outString); //xiaoqiang outString = decoder.write(Buffer.from([0xA2])); console.log(outString); //¢ //單雙字節混合,置于中間 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0xC2, 0x69, 0x61, 0x6e, 0x67])); console.log(outString); //xiaoq?iang outString = decoder.write(Buffer.from([0xA2])); console.log(outString); //? //單雙字節混合,置于開始 outString = decoder.write(Buffer.from([0xC2, 0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67])); console.log(outString); //?xiaoqiang outString = decoder.write(Buffer.from([0xA2])); console.log(outString); //? //單雙字節混合,置于末尾 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 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, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67])); console.log(outString); //xiaoqiang outString = decoder.end(); console.log(outString); // //單雙字節混合,置于末尾 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 0xC2])); console.log(outString); //xiaoqiang outString = decoder.end(Buffer.from([0xA2])); console.log(outString); //¢ //單雙字節混合,置于末尾 outString = decoder.write(Buffer.from([0x78, 0x69, 0x61, 0x6f, 0x71, 0x69, 0x61, 0x6e, 0x67, 0xC2])); console.log(outString); //xiaoqiang outString = decoder.end(); console.log(outString);
以上就是關于Node.js API中怎么使用string_decoder的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。