JavaScript Blobs and object URLs
In this article, we'll learn about blobs and object URLs in JavaScript. It's possible that you'll want to use JavaScript to store data that was generated by a program in a file at some point. In situations like this, blobs and object URLs can be very helpful.
A file-like object that can be used to represent raw data that cannot be changed is called a Blob object. Blob objects are extremely helpful for storing dynamic content in browsers as a result of the fact that they include metadata that describes the data they store, including its type and size. Let's say you want to store the JSON response that was returned to you by a REST API in the browser as a file:
Using JavaScript Blobs to save JSON as a file
Suppose you want to store the JSON response from a REST API as a local file:
fetch('YOUR_API_URL')
.then(res => res.json())
.then(data => {
// Transfrom the JSON object to a blob
})
.catch(err => console.error(err));
It is necessary to first convert the JSON data to a JSON string before creating an instance of the Blob using its constructor. Here is how:
// Transform JSON to string
const dataStr = JSON.stringify(data);
// Create a Blob object
const blob = new Blob([dataStr], { type: 'application/json' });
The URL.createObjectURL() function can be used to convert unstructured blob data into an object URL. If you need to generate a URL for a blob or file, you can use this method to do so as follows:
const url = URL.createObjectURL(blob);
After that you can use the instructions in this article to download the file.
Next, you need to release the object. When an object URL is created, it will be stored in the Document Object Model (DOM) indefinitely. If you close your browser or reload the page, all of the object URLs will be released.
However, whenever possible, it is recommended to release object URLs to optimize performance and reduce memory consumption. The URL.revokeObjectURL() method can be utilized to free URL objects:
URL.revokeObjectURL(url);
-
Date: