How to write data to a file using only JavaScript?

Spread the love

Sometimes, we want to write data to a file using only JavaScript.

In this article, we’ll look at how to write data to a file using only JavaScript.

How to write data to a file using only JavaScript?

To write data to a file using only JavaScript, we can create a link.

For instance, we write

const a = document.createElement("a");
a.href = "data:application/octet-stream," + encodeURIComponent("My DATA");
a.download = "abc.txt";
a.click();

to create a link with createElement.

Then we set its href property to a base64 URL string with the file data.

And we set its download property to a string with the downloaded file’s name.

Then we call click to download the file.

Conclusion

To write data to a file using only JavaScript, we can create a link.

Leave a Reply

Your email address will not be published. Required fields are marked *