Trusted answers to developer questions

What is the setEncoding function in Node.js?

Rukhshan Haroon

Grokking the Behavioral Interview

Get Educative’s popular interview prep course for free.

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.




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.


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 streams
const file1 = file_stream.createReadStream("file1.txt");
const file2 = file_stream.createReadStream("file2.txt");
//setting encoding of file 1 to hex
//printing each data-element of file 1
file1.on('data', (data_element) => {
//setting encoding of file 2 to utf8
//printing each-data element of file 2
file2.on('data', (data_element) => {

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




Rukhshan Haroon
Copyright ©2023 Educative, Inc. All rights reserved
Trusted Answers to Developer Questions

Related Tags

Keep Exploring
Related Courses