Node.js stringDecoder.end() Method
Last Updated :
08 Oct, 2021
The stringDecoder.end() method is used to return all the remaining input stored in the internal buffer as a string. This method ensures that any incomplete UTF-8 and UTF-16 characters are replaced with substitution characters that are appropriate for character encoding.
When the optional buffer argument is provided, the stringDecoder.write() method is called once with the data before returning the remaining buffer input.
Syntax:
stringDecoder.end( [buffer] )
Parameters: This function accepts single parameter as mentioned above and described below:
- buffer: It is a Buffer, TypedArray, or DataView that contains the bytes that have to be decoded. It is an optional parameter.
Return Value: It returns the remaining input stored in a buffer as a string.
Below programs illustrate the stringDecoder.end() method in Node.js:
Example 1:
Javascript
const { StringDecoder } = require( "string_decoder" );
const decoder = new StringDecoder( "utf-8" );
const text_one = Buffer.from( "GeeksforGeeks" , "utf-8" );
let decoded_text = decoder.end(text_one);
console.log( "Decoded Text:" , decoded_text);
console.log( "Decoding the Euro Symbol:" );
console.log(decoder.write(Buffer.from([0xE2])));
console.log(decoder.write(Buffer.from([0x82])));
console.log(decoder.end(Buffer.from([0xAC])));
|
Output:
Decoded Text: GeeksforGeeks
Decoding the Euro Symbol:
€
Example 2:
Javascript
const { StringDecoder } = require( "string_decoder" );
const decoder = new StringDecoder( "utf-8" );
let cent_symbol = Buffer.from([0xc2, 0xa2]);
let cent_symbol_out = decoder.end(cent_symbol);
console.log( "Complete Cent Symbol:" , cent_symbol_out);
cent_symbol = Buffer.from([0xc2]);
cent_symbol_out = decoder.write(cent_symbol);
console.log( "Cent Symbol using write():" ,
cent_symbol_out);
cent_symbol = Buffer.from([0xc2]);
cent_symbol_out = decoder.end(cent_symbol);
console.log( "Cent Symbol using end():" ,
cent_symbol_out);
|
Output:
Complete Cent Symbol: ¢
Cent Symbol using write():
Cent Symbol using end(): ??
Reference: https://nodejs.org/api/string_decoder.html#string_decoder_stringdecoder_end_buffer
Share your thoughts in the comments
Please Login to comment...