How to Create and Save text file in JavaScript
As we know that JavaScript is one of the most popular high-level, interpreted programming language in the world. Now it is capable to do almost everything that we are doing in other programming languages. To know more about check out the StackOverflow 2018 survey.
What we’ll build
In this tutorial, we will create and save the data into a text file. To do that we’ll write:
- A JavaScript function that fire on the button click event.
- Create a
Blob
constructor, pass the data in it to be to save and mention the type of data. - And finally, call the
saveAs(Blob object, "your-file-name.text")
function of FileSaver.js library.
Note: To create and save data into a text file, I have used a third party FileSaver.js library.
Let’s jump into the actual juicy part of the code.
1. Saving static data
1.1 Create a function that executes on button click event.
function saveStaticDataToFile() {
}
1.2 Instantiate the Blob
object and pass a text string as the first parameter and blob type as the second parameter.
var blob = new Blob(["Welcome to Websparrow.org."],
{ type: "text/plain;charset=utf-8" });
1.3 Now call the saveAs
function which takes blob object as input and let you save files on web browser.
saveAs(blob, "static.txt");
Check out the complete example.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Create and Save text file in JavaScript</title>
<script src="js/FileSaver.js"></script>
<script>
function saveStaticDataToFile() {
var blob = new Blob(["Welcome to Websparrow.org."],
{ type: "text/plain;charset=utf-8" });
saveAs(blob, "static.txt");
}
</script>
</head>
<body>
<button type="button" onclick="saveStaticDataToFile();">Click to Save</button>
</body>
</html>
2. Saving dynamic data
To save user input data into a text file, first, we need to store user’s data into a variable and pass that variable as Blob
first parameter. Check out the complete code example.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Create and Save text file in JavaScript</title>
<script src="js/FileSaver.js"></script>
<script>
function saveDynamicDataToFile() {
var userInput = document.getElementById("myText").value;
var blob = new Blob([userInput], { type: "text/plain;charset=utf-8" });
saveAs(blob, "dynamic.txt");
}
</script>
</head>
<body>
<textarea id="myText" rows="4" cols="50">
We love to share our experiments, ideas, and knowledge with everyone by writing articles on the latest technology trends.
</textarea>
<button type="button" onclick="saveDynamicDataToFile();">Click to Save</button>
</body>
</html>
Remember: Don’t forget to import FileSaver.js library in your document (html/jsp/etc).
Done. Thank You 🙂