What is setDefaultEncoding in Node.js?
The setDefaultEncoding method in Node.js comes with the Stream module and is used to reset the default encoding of a writable stream.
Syntax
stream.setDefaultEncoding(encoding)
Parameters
The setDefaultEncoding function only takes one argument:
encoding: a string that denotes the new default encoding
Some of the most widely used encoding(s) supported by Node.js are listed below:
Return value
The setDefaultEncoding function returns the current state of the writable stream, which contains details such as its default encoding and length.
Example
The program below creates a writable stream. A string is written to it, and the setDefaultEncoding method is called to change its default encoding from hex to utf8.
To observe this change, the stream’s current default encoding value is filtered out and printed onto the screen using the console.log function.
Alternatively, the entire state of the stream can be printed as well by skipping the filter. The state is returned by the setDefaultEncoding function, or it can be accessed by directly logging the stream onto the console.
const stream = require('stream');//creating a new writable streamconst mystream = new stream.Writable({//function to write data to the streamwrite: function(data) {//prints data onto the consoleconsole.log("Data in stream:",data.toString())}});// writes data to streammystream.write('Educative');//changing default encoding of stream to hexmystream.setDefaultEncoding("hex");//print default encoding of streamconsole.log("Current default encoding:", mystream['_writableState']['defaultEncoding'])//changing default encoding of stream to hexmystream.setDefaultEncoding("utf8");//print new default encoding of streamconsole.log("New default encoding:",mystream[ '_writableState']['defaultEncoding'])//to print the entire state, use the line below://console.log(mystream)
Free Resources