The setEncoding
function in Node.js alters the encoding of character data stored inside a readable stream. It comes as part of the stream
module.
By changing character encodings, programmers can use the setEncoding
method to interpret the same piece of data in multiple ways.
readable_stream.setEncoding(encoding)
The setEncoding
function takes in only one parameter:
encoding
: a string that denotes the encoding in which the programmer wishes to interpret the data stored in a readable stream.If the programmer does not specify an encoding, it is not set to any default value.
Some of the most common character encoding(s) supported by Node.js are listed below.
The setEncoding
function returns a string that contains data read from a readable stream in the encoding specified by the programmer. If an encoding is not specified, a buffer is returned instead.
In the example below, we read data from two files using the createReadStream
method and create two file objects.
Subsequently, we use the setEncoding
method to decode data from each stream using a different character encoding.
Using the console.log
function, we output all the data elements of each stream onto the console and observe the output, since it depends on the encoding used to interpret it.
const file_stream = require('fs');//creatomg two readable streamsconst file1 = file_stream.createReadStream("file1.txt");const file2 = file_stream.createReadStream("file2.txt");//setting encoding of file 1 to hexfile1.setEncoding('hex');//printing each data-element of file 1file1.on('data', (data_element) => {console.log(data_element);});//setting encoding of file 2 to utf8file2.setEncoding('utf8');//printing each-data element of file 2file2.on('data', (data_element) => {console.log(data_element);});
Note that both files contain identical data, but have completely different outputs.
Free Resources