How to save binary data as file using JavaScript from a browser?

Sometimes,. we want to save binary data as file using JavaScript from a browser.

In this article, we’ll look at how to save binary data as file using JavaScript from a browser.

How to save binary data as file using JavaScript from a browser?

To save binary data as file using JavaScript from a browser, we create a link programmatically.

For instance, we write

const a = document.createElement("a");
const blob = new Blob(data, { type: "octet/stream" });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);

to create a link with createElement.

Then we create a Blob from the data string which has the data to download.

Next, we convert it to a base64 URL string with createObjectURL.

Then we set the href to the url.

Next we set the file name of the downloaded file by setting the download property.

Then we call click to download the file.

Finally we call revokeObjectURL to clear the URL resource.

Conclusion

To save binary data as file using JavaScript from a browser, we create a link programmatically.