What is the setEncoding function in Node.js?

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.

Syntax

readable_stream.setEncoding(encoding)

Parameters

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.

%0 node_1625944649818 hex node_1625944550064 base64 node_1625944582475 ucs2 node_1625944546352 ascii node_1625944524409 latin1 node_1 utf8
Common character encoding(s) supported by Node.js

Return value

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.

Example

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.

index.js
file2.txt
file1.txt
const file_stream = require('fs');
//creatomg two readable streams
const file1 = file_stream.createReadStream("file1.txt");
const file2 = file_stream.createReadStream("file2.txt");
//setting encoding of file 1 to hex
file1.setEncoding('hex');
//printing each data-element of file 1
file1.on('data', (data_element) => {
console.log(data_element);
});
//setting encoding of file 2 to utf8
file2.setEncoding('utf8');
//printing each-data element of file 2
file2.on('data', (data_element) => {
console.log(data_element);
});

Note that both files contain identical data, but have completely different outputs.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved