当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js stringDecoder.end()用法及代码示例


stringDecoder.end()方法用于返回存储在内部缓冲区中的所有剩余输入作为字符串。此方法确保将所有不完整的UTF-8和UTF-16字符替换为适合字符编码的替换字符。

提供可选的buffer参数后,stringDecoder.write()在返回剩余的缓冲区输入之前,对数据调用一次方法。

用法:

stringDecoder.end( [buffer] )

参数:该函数接受上述和以下描述的单个参数:

  • buffer:它是一个Buffer,TypedArray或DataView,其中包含必须解码的字节。它是一个可选参数。

返回值:它以字符串形式返回存储在缓冲区中的其余输入。



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

范例1:

// Import the string_decoder module 
// and get the StringDecoder class  
// using object destructuring 
const { StringDecoder } = require("string_decoder"); 
  
const decoder = new StringDecoder("utf-8"); 
  
// Using the end() method 
const text_one = Buffer.from("GeeksforGeeks", "utf-8"); 
let decoded_text = decoder.end(text_one); 
console.log("Decoded Text:", decoded_text); 
  
// The Euro Symbol is denoted using 
// the bytes [0xE2, 0x82, 0xAC] 
  
console.log("Decoding the Euro Symbol:"); 
  
// Decoding the euro symbol 
// Using the write() method to 
// write the first two parts 
console.log(decoder.write(Buffer.from([0xE2]))); 
console.log(decoder.write(Buffer.from([0x82]))); 
  
// Finishing the symbol using the end() method 
// with that gives an additonal call to write() 
// using the last part of the buffer 
console.log(decoder.end(Buffer.from([0xAC])));

输出:

Decoded Text:GeeksforGeeks
Decoding the Euro Symbol:


€

范例2:

// Import the string_decoder module 
// and get the StringDecoder class  
// using object destructuring 
const { StringDecoder } = require("string_decoder"); 
const decoder = new StringDecoder("utf-8"); 
// The Cent Symbol is denoted using 
// Buffer.from([0xc2, 0xa2]) 
  
// Decoding the complete cent symbol from buffer 
let cent_symbol = Buffer.from([0xc2, 0xa2]); 
let cent_symbol_out = decoder.end(cent_symbol); 
console.log("Complete Cent Symbol:", cent_symbol_out); 
  
// Decoding incomplete cent symbol using 
// Buffer.write() method 
cent_symbol = Buffer.from([0xc2]); 
cent_symbol_out = decoder.write(cent_symbol); 
console.log("Cent Symbol using write():", 
                       cent_symbol_out); 
  
// Decoding incomplete cent symbol 
// using Buffer.end() method 
cent_symbol = Buffer.from([0xc2]); 
cent_symbol_out = decoder.end(cent_symbol); 
console.log("Cent Symbol using end():", 
                     cent_symbol_out);

输出:

Complete Cent Symbol:¢
Cent Symbol using write():
Cent Symbol using end():??

参考: https://nodejs.org/api/string_decoder.html#string_decoder_stringdecoder_end_buffer




相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | stringDecoder.end() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。