save file with javascript
Javascript Web Development

How to generate text file with Javascript

For whatever reasons, you might want to generate text file with javascript dynamically and let user download it without involvement of server side script. In this tutorial, I’ll show you how to do that in a couple minutes!

To create a text file from javascript, we’ll need to use Blob object. Blob (A Binary Large OBject) is a collection of binary data stored as a single entity. So, we’re going to create a Blob object that contains our text content. Then we’ll convert a blob into a text file which web browser will then popup the download dialog box for the users. This might sounds difficult but if you know the right tools, it’s just a couple lines of code. This solution is also cross browsers support (Well, I mean modern browsers as this won’t work with IE9 and below)

Assume that you already have your button binded with click event. (Code below uses jQuery)

$("#save-btn").click(function() { 
   
});

We’ll use Blob() constructor and pass our text string as first parameter. Noted that we have to put it in array form. The second parameter, we’ll define our blob type as plain text with utf-8 encoding.

$("#save-btn").click(function() { 
   var blob = new Blob(["This is my first text."], {type: "text/plain;charset=utf-8"});
});

Now we have our blob object, next we’ll need to convert it to text file. There is a very nice javascript plugin calls Filesaver.js take blob object as input and let you save files on web browser. After included the filesaver.js to your page, use saveAs() to trigger the download popup dialog.

$("#save-btn").click(function() { 
   var blob = new Blob(["This is my first text."], {type: "text/plain;charset=utf-8"});
   saveAs(blob, "testfile1.txt");
});

Please see video tutorial below for step by step instruction.

Lastly, don’t forget to checkout our Youtube Channel for other interesting tutorials or leave the comment below if you have any questions or feedback. Thanks!

Red Stapler Channel: https://www.youtube.com/c/RedStapler_channel

2 comments

Leave a Reply

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