當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Node.js stringDecoder.write()用法及代碼示例


stringDecoder.write()方法用於從給定的Buffer,TypedArray或DataView返回解碼後的字符串。此方法還確保從返回的字符串中忽略緩衝區末尾的任何不完整的多字節字符。這些字符存儲在內部緩衝區中,以供下次調用stringDecoder.write()或者stringDecoder.end()方法。

用法:

stringDecoder.write( buffer )

參數:此方法接受上述和以下描述的單個參數:

  • buffer:它是一個Buffer,TypedArray或DataView,其中包含必須解碼的字節。

返回值:它返回從給定緩衝區解碼的字符串。

以下示例程序旨在說明Node.js中的stringDecoder.write()方法:



範例1:

// Node.js program to demonstrate the    
// stringDecoder.write() Method  
  
// Import the string_decoder module 
// and get the StringDecoder class  
// using object destructuring 
const { StringDecoder } = require("string_decoder"); 
  
// Create a new instance of the decoder 
const decoder = new StringDecoder("utf-8"); 
  
const text_one = Buffer.from("GeeksforGeeks", "utf-8"); 
let decoded_text = decoder.write(text_one); 
console.log("Decoded Text:", decoded_text);

輸出:

Decoded Text:GeeksforGeeks

範例2:

// Node.js program to demonstrate the    
// stringDecoder.write() Method  
  
// Import the string_decoder module 
// and get the StringDecoder class  
// using object destructuring 
const { StringDecoder } = require("string_decoder"); 
  
// Create a new instance of the decoder 
const decoder = new StringDecoder("utf-8"); 
  
// Decoding text using hex from buffer 
const hex_text = new Buffer.from( 
      "4765656B73666F724765656B73", "hex"); 
let decoded_hex_text = decoder.write(hex_text); 
console.log("Decoded Text Hex:", decoded_hex_text); 
  
// Decoding text using base64 from buffer 
const base64_text = new Buffer.from( 
      "R2Vla3Nmb3JHZWVrcw==", "base64"); 
let decoded_base64_text = decoder.write(base64_text); 
console.log("Decoded Text Base64:", decoded_base64_text); 
  
// Decoding the cent symbol from buffer 
const cent_symbol = Buffer.from([0xc2, 0xa2]); 
let cent_symbol_out = decoder.write(cent_symbol); 
console.log("Cent Symbol:", cent_symbol_out);

輸出:

Decoded Text Hex:GeeksforGeeks
Decoded Text Base64:GeeksforGeeks
Cent Symbol:¢

參考: https://nodejs.org/api/string_decoder.html#string_decoder_stringdecoder_write_buffer




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | stringDecoder.write() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。