Node.js TextEncoder
The TextEncoder is an interface that takes a stream of code points as input and emits a stream of encoded UTF-8 codes. This is provided in NodeJS as an implementation of the WHATWG Encoding Standard ‘TextEncoder’ API. All instances of TextEncoder only support UTF-8 encoding.
UTF-8: It is an encoding mechanism that encodes in multiple 8 bits. It is capable of encoding all 1,112,064 characters in 4 bytes, each of 8 bits. The first 128 characters match the ASCII mapping.
Import:
var util = require('util');
Syntax:
util.TextEncoder( );
Constructor:
- TextEncoder( ): This method will return an new object of TextEncoder class which can generated encoding of UTF-8 format.
Properties:
The TextEncoder class does not inherit any property. Only one property is defined which is:
- TextEncoder.prototype.encoding: It is a read-only property that returns a string of the name of the encoding used by the object. It always returns UTF-8.
Functions:
- encode(string): returns Uint8Array from a ‘string’.
- encodeInto(string, dest): takes two parameters Input first is the input string and the second is the output array. It encodes ‘string’ into ‘dest’ that must be Uint8Array.
Return Value: Returns an array corresponding to encoding format containing code points representing input.
Example 1: We will encode and save the output in a local variable and print it on the console to check the encoded value. Create a file index.js and write the below code:
Javascript
var util = require( 'util' ); let encoder = new util.TextEncoder(); let uint8Array = encoder.encode( "Hello" ); console.log(uint8Array); |
Steps to run the application: Write the below command in the terminal to start the server:
node index.js
Output:
Uint8Array [ 72, 101, 108, 108, 111 ]
Example 2: We will now encode the string into an output array bigger than the size of the input to see how they function encodes. Create a file index.js and write the below code:
Javascript
var util = require( 'util' ); let encoder = new util.TextEncoder(); let src = "Hello" ; let uint8Array = new Uint8Array(10); encoder.encodeInto(src, uint8Array); console.log(uint8Array); |
Steps to run the application: Write the below command in the terminal to start the server:
node index.js
Output:
Uint8Array(10) [ 72, 101, 108, 108, 111,0, 0, 0, 0, 0]
Browser Compatibility:
BROWSER | VERSION SUPPORTED |
Chrome | 38 |
Edge | 79 |
Firefox | 18 |
Internet Explorer | NOT SUPPORTED |
Opera | 25 |
Safari | 10.1 |
Android WebView | 38 |
Deno | 1.0 |
NodeJS | 8.3.0 |
Samsung Internet | 3.0 |
Safari iOS | 10.3 |
Reference: https://nodejs.org/api/util.html#class-utiltextencoder
Contact Us