JavaScript - Convert Byte Array to String
Last Updated :
26 Nov, 2024
Improve
Here are the various methods to convert Byte Array to string in JavaScript.
1. Using WebAPI TextDecoder.decode() Method
The TextDecoder API is a modern and efficient way to convert a byte array (Uint8Array) to a string. It’s supported in both browsers and Node.js.
const byteA = new Uint8Array([72, 101, 108, 108, 111]);
const s = new TextDecoder().decode(byteA);
console.log(s);
Output
Hello
- A TextDecoder object is created, which can decode byte arrays.
- The decode method converts the byte array to a string.
2. Using Buffer and toString() Method (Node.js)
In Node.js, the Buffer class provides a toString method to decode byte arrays into strings.
const byteA = Buffer.from([72, 101, 108, 108, 111]);
const s = byteA.toString("utf-8");
console.log(s);
Output
Hello
- Buffer.from() converts the byte array into a Node.js Buffer.
- The toString() method decodes the buffer into a string.
3. Using String.fromCharCode() Method
This method uses String.fromCharCode to convert each byte in the array into a character.
const byteA = [72, 101, 108, 108, 111];
const s = String.fromCharCode(...byteA);
console.log(s);
Output
Hello
- The spread operator (...) expands the byte array into individual arguments.
- String.fromCharCode converts each byte to its corresponding character.
4. Using Base64 Encoding and Decoding
This approach involves encoding the byte array into Base64 and decoding it to a string.
const byteA = new Uint8Array([72, 101, 108, 108, 111]);
const base64 = btoa(String.fromCharCode(...byteA));
const s = atob(base64);
console.log(s);
Output
Hello
- btoa encodes the byte array into a Base64 string.
- atob decodes the Base64 string back to the original string.
5. Using TextDecoder.decode() with Node.js Buffer
You can combine TextDecoder and Buffer for a modern, efficient approach in Node.js.
const byteA = Buffer.from([72, 101, 108, 108, 111]);
const s = new TextDecoder().decode(byteA);
console.log(s);
Output
Hello
- Buffer.from() converts the array to a Buffer.
- TextDecoder.decode() decodes the Buffer to a string.
6. Using the String Constructor with Array.join() Method
This method uses Array.join to create a string representation of the byte array.
const byteA = [72, 101, 108, 108, 111];
const s = byteA.map(byte => String.fromCharCode(byte)).join("");
console.log(s);
Output
Hello
Which Approach Should You Use?
Approach | When to Use |
---|---|
TextDecoder.decode() | Best for modern web or Node.js projects; works well with UTF-8 data. |
Buffer and toString() | Ideal for Node.js environments. |
String.fromCharCode() | Simple and effective for small arrays. |
Base64 Encoding and Decoding | Use when working with Base64 encoding/decoding. |
TextDecoder.decode() with Buffer | A modern, efficient combination for Node.js projects. |
String Constructor with Array.join() | Customizable but less efficient for large arrays. |