How to useTextDecoder.decode() with Node.js Buffer in Javascript
In Node.js environments, you can also utilize the TextDecoder class along with Node.js Buffer to decode byte arrays into strings.
// Importing the TextDecoder class from Node.js
const { TextDecoder } = require('util');
// Creating a new byte array using Buffer
let byteArray = Buffer.from([
71, 101, 101, 107, 115, 102, 111,
114, 71, 101, 101, 107, 115,
]);
// Creating a TextDecoder instance with UTF-8 encoding
const decoder = new TextDecoder('utf-8');
// Decoding the byte array into a string
const str = decoder.decode(byteArray);
// Display the output
console.log(str);
Output
w3wiki
How to Convert Byte Array to String in JavaScript ?
A Byte array is an array containing encoded data in the form of unsigned integers. It canât be used directly. We have to decode it to get the meaning full data out of it. In this article, we will learn the conversion of a given byte array to a string of characters.
Various approaches to convert byte array to string are as follows:
Table of Content
- Using WebAPI TextDecoder.decode() Method
- Using Buffer and toString() Methods
- Using JavaScript string.fromCharCode() Method
- Using Base64 Encoding and Decoding
- Using TextDecoder.decode() with Node.js Buffer
- Using the String constructor with Array.join
Contact Us