GUIDES Binary Data Convert ArrayBuffers to String
About
Binary Data
Index
Convert String to ArrayBuffer
Convert ArrayBuffer to String
Convert ArrayBuffers to String
Handle Errors Converting ArrayBuffer to String
Immutable ArrayBuffers
Resize an ArrayBuffer
Combine ArrayBuffers
Convert Base64 to Binary Data
Convert Binary Data to Base64
Convert Binary Data to Hex
Convert Hex to Binary Data
Calculate CRC for Binary Data
Compress Binary Data – One Buffer
Compress Binary Data – Streaming
Decompress Binary Data – One Buffer
Decompress Binary Data – Streaming
Callbacks
Index
One-Time Callback
Repeating Callback
Repeating Callback with Initial Delay
Immediate Callback
Reschedule Callback
Cancel Callback
Suspend Callback
What About setTimeout?
Optimizing Embedded JavaScript
Index
When to Optimize
Know Where to Optimize
Looping through an Array
Iterating Over a String
Building a String
Avoid Copying Buffers
Accessing Properties
Map versus Object
Appending to an Array
Operating on Bits
Defining Class Methods
Reducing Stack Use
Time
Index
Get Unix Time
Get Time of Day
Get Date
Get Time Since System Start
Get Microseconds
Set System Date and Time
Set Real-Time Clock Time
Get Time and Date from Network
Get Time and Date from Real-Time Clock
Sleep

Convert ArrayBuffers to String

The TextDecoder handles multi-byte UTF-8 sequences split across buffers using the stream option of its decode() method.

The stream option is useful for text received in fragments, such as serial data from a UART or the body of an HTTP response.

// UTF-8 values for "forêt"
const bytes = Uint8Array.of(102, 111, 114, 195, 170, 116);
const decoder = new TextDecoder;

// first part, splitting the "ê"
let string = decoder.decode(bytes.buffer.slice(0, 4), {stream: true});
// => "for"

// second part, splitting the "ê"
string += decoder.decode(bytes.buffer.slice(4));
// => "forêt"

The decode() method accepts any Byte Buffer. The above example can be rewritten using subarray() instead of slice() to eliminate a copy of the data.

// UTF-8 values for "forêt"
const bytes = Uint8Array.of(102, 111, 114, 195, 170, 116);
const decoder = new TextDecoder;

 // first part, splitting the "ê"
let string = decoder.decode(bytes.subarray(0, 4), {stream: true});
// => "for"

 // second part, splitting the "ê"
string += decoder.decode(bytes.subarray(4));
// => "forêt"

To use TextDecoder you need to import its module in your module...

import TextDecoder from "text/decoder"; 

...and to include its manifest in your manifest.

{
	"include": [
		"$(MODDABLE)/modules/data/text/decoder/manifest.json"
	]
}