Javascript - I created a blob from a string, how do I get the string back out?
To extract a string from a Blob, use the FileReader.readAsText() method as follows:
FileReader loads the blob and the onload event is triggered when the loading completes, outputting the string.
Opera of Blob reading methods
Sure, FileReader is the marquee name, but JavaScript has a ton of other supporting characters that can also read a nice Blob.
Async Blob Reading: World, meet blob.text()
The starlet here, blob.text(), returns a promise that resolves to a text string.
Blob in a Response: It’s a Promise!
Turn that Blob into a Response object and use .text() method that, you guessed it, returns a promise.
Let fetch() do the heavy lifting
Another way is by creating a blob URI with URL.createObjectURL(). Remember to URL.revokeObjectURL() or you’ll have memory leaks haunt you.
The elegant async/await ballet
A modern approach involves using async/await. More readability, less "callback hell".
Remember, error handling is your safety net in this asynchronous trapeze act. Use try/catch.
Keeping data on a short leash
Blob Type: Your safety harness
Specify the type when you're creating a Blob or your data might try out some unexpected transformations:
Strings as Arrays: The Trojan Horse
Wrap strings in an array when sending them to Blob constructor, and your data format can ride along safely inside:
Access Blob Data: Timing is key
Access the Blob data only within the FileReader.onload event to ensure you're not showing up early to the party:
Was this article helpful?