Convert Blob to String in JavaScript

Using the FileReader API readAsText method

TL;DR: Use the readAsText() method.
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn’t necessarily in a JavaScript-native format. (https://developer.mozilla.org/en/docs/Web/API/Blob)

Sometimes we get Blobs instead of plain text as responses when getting a resource from an API. This is important especially when the response indicates an error occurred and the description of the error is stored in that Blob. Hence, you are hard-pressed to read the content of the Blob.

To read it, you need to convert it to a string — and one easy way of doing that is using the FileReader API.

The FileReader API has a couple of useful methods like readDataAsUrl(), but right now we’re interested in the readAsText() method. This method accepts a Blob and reads it as text, which is pretty obvious going by its name.

You might be asking:

Why does the readAsText method accept a blob? Isn’t it supposed to read files because it’s part of the FileReader API?

It’s because:

The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Calling the readAsText method won’t actually return the text. Instead, it fires a an event called loadend after it finishes reading the content of the blob. You have to handle this event in order to access the content of the blob as text. That text is stored in e.srcElement.result, where e is the event object.

Example

Did you find this useful? If you did, click the little green button below and follow me! Many thanks! ^_^
Personal Pages: http://johnpaulada.github.io
Like what you read? Give John Paul Ada a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.