首頁  >  文章  >  web前端  >  Nodejs中使用string_decoder模組將buffer轉成string

Nodejs中使用string_decoder模組將buffer轉成string

青灯夜游
青灯夜游轉載
2021-05-14 11:00:362636瀏覽

這篇文章要跟大家介紹一下Nodejs中使用string_decoder模組將buffer轉成string的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

Nodejs中使用string_decoder模組將buffer轉成string

模組簡介

#string_decoder模組用於將Buffer轉成對應的字串。使用者透過呼叫stringDecoder.write(buffer),可以獲得buffer對應的字串。 【推薦學習:《nodejs 教程》】

它的特殊之處在於,當傳入的buffer不完整(例如三個字節的字符,只傳入了兩個),內部會維護一個internal buffer將不完整的位元組cache住,等到使用者再次呼叫stringDecoder.write(buffer)傳入剩餘的位元組,來拼成完整的字元。

這樣可以有效避免buffer不完整帶來的錯誤,對於許多場景,例如網路請求中的包體解析等,非常有用。

入門範例

這節分別示範了decode.write(buffer)decode.end([buffer])兩個主要API的用法。

例子一:

decoder.write(buffer)呼叫傳入了Buffer物件4906621e4f28d4de4703165e1c48080e,對應的回傳了對應的字串;

const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');

// Buffer.from(&#39;你&#39;) => <Buffer e4 bd a0>
const str = decoder.write(Buffer.from([0xe4, 0xbd, 0xa0]));
console.log(str);  // 你

例子二:

decoder.end([buffer])被呼叫時,內部剩餘的buffer會被一次回傳。如果此時帶上buffer參數,那麼相當於同時呼叫decoder.write(buffer)decoder.end()

const StringDecoder = require(&#39;string_decoder&#39;).StringDecoder;
const decoder = new StringDecoder(&#39;utf8&#39;);

// Buffer.from(&#39;你好&#39;) => <Buffer e4 bd a0 e5 a5 bd>
let str = decoder.write(Buffer.from([0xe4, 0xbd, 0xa0, 0xe5, 0xa5]));
console.log(str);  // 你

str = decoder.end(Buffer.from([0xbd]));
console.log(str);  // 好

範例:分多次寫入多個位元組

下面的例子,示範了分多次寫入多個位元組時, string_decoder模組是怎麼處理的。

首先,傳入了efba047232e9c30493e472f2bf6fc120還差1個位元組,此時,decoder.write (xx)返回

然後,再呼叫decoder.write(Buffer.from([0xbd])),將剩餘的1個位元組傳入,成功回傳

const StringDecoder = require(&#39;string_decoder&#39;).StringDecoder;
const decoder = new StringDecoder(&#39;utf8&#39;);

// Buffer.from(&#39;你好&#39;) => <Buffer e4 bd a0 e5 a5 bd>
let str = decoder.write(Buffer.from([0xe4, 0xbd, 0xa0, 0xe5, 0xa5]));
console.log(str);  // 你

str = decoder.write(Buffer.from([0xbd]));
console.log(str);  // 好

範例:decoder.end()時,當位元組數不完整的處理

decoder.end(buffer)時,僅傳入了的第1個字節,此時呼叫decoder.end(),回傳了,對應的buffer為&lt ;Buffer ef bf bd>

const StringDecoder = require(&#39;string_decoder&#39;).StringDecoder;

// Buffer.from(&#39;好&#39;) => <Buffer e5 a5 bd>
let decoder = new StringDecoder(&#39;utf8&#39;);
let str = decoder.end( Buffer.from([0xe5]) );
console.log(str);  // �
console.log(Buffer.from(str));  // <Buffer ef bf bd>

官方文件對於這種情況的解釋是這樣的(跟廢話差不多),大約是約定俗成了,當utf8碼點無效時,替換成ef bf bd

Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character be replaced with substitution characters appropriate for the character be replaced##.

#相關連結

你應該記住的一個UTF-8字元「EF BF BD」http://liudanking.com/golang/utf-8_replacement_character/

更多程式相關知識,請造訪:

程式設計影片

! !

以上是Nodejs中使用string_decoder模組將buffer轉成string的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除