Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Create and Save text file in JavaScript?
In this tutorial, we will learn to create and save text files in JavaScript. Sometimes, developers need to get text content from users and allow them to store it in a text file that can be downloaded to their local computer.
JavaScript provides native methods to achieve this, and we can also use third-party libraries like FileSaver.js for enhanced functionality.
Create a Text File Using Native JavaScript
We can use native JavaScript operations to create and save text files on the user's computer. The approach uses the HTML <a> tag with the Blob API to create downloadable files.
Syntax
// Create element with <a> tag
const link = document.createElement("a");
// Create a Blob object with the file content
const file = new Blob([content], { type: 'text/plain' });
// Add file content in the object URL
link.href = URL.createObjectURL(file);
// Add file name
link.download = "sample.txt";
// Trigger download by clicking the link
link.click();
// Clean up the object URL
URL.revokeObjectURL(link.href);
How It Works
The process follows these steps:
Step 1 ? Create an HTML <a> element programmatically.
Step 2 ? Get content to add to the text file.
Step 3 ? Create a Blob object containing the content.
Step 4 ? Generate an object URL and assign it to the href attribute.
Step 5 ? Set the download attribute with the desired filename.
Step 6 ? Programmatically click the link to trigger the download.
Example
In this example, users can enter content in a textarea and click "Save File" to download it as a text file:
<html>
<body>
<h2>Create a text file and save it to local computer using JavaScript</h2>
<p>Enter the file content:</p>
<textarea placeholder="Enter your text here..."></textarea>
<br/><br/>
<button onclick="downloadFile()">Save File</button>
<script>
const downloadFile = () => {
const link = document.createElement("a");
const content = document.querySelector("textarea").value;
if (!content.trim()) {
alert("Please enter some content!");
return;
}
const file = new Blob([content], { type: 'text/plain' });
link.href = URL.createObjectURL(file);
link.download = "sample.txt";
link.click();
URL.revokeObjectURL(link.href);
};
</script>
</body>
</html>
Using FileSaver.js Library
FileSaver.js is a popular JavaScript library that simplifies file creation and downloading. It provides better cross-browser compatibility and additional features.
Syntax
// Create blob object with file content
const blob = new Blob(["This is sample file content."], {
type: "text/plain;charset=utf-8"
});
// Save the file using FileSaver library
saveAs(blob, fileName);
Parameters
The saveAs function accepts these parameters:
blob ? The Blob object containing file content.
filename ? The default filename when downloading.
Example
This example demonstrates creating a text file with predefined content using the FileSaver library:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
</head>
<body>
<h2>Create text file using <i>FileSaver</i> JavaScript Library</h2>
<button type="button" onclick="createTextFile()">Create Text File</button>
<script>
function createTextFile() {
const blob = new Blob(["This is sample file content created using FileSaver.js library."], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, "download.txt");
}
</script>
</body>
</html>
Converting File Content to Text
You can also create text files from other file types. This example shows how to convert an uploaded image file's binary content into a text file:
Example
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
</head>
<body>
<h2>Upload image and save its content as text file</h2>
<input type="file" id="uploadedImage" accept="image/png, image/gif, image/jpeg"/>
<script>
const element = document.getElementById("uploadedImage");
element.onchange = function (event) {
const file = event.target.files[0];
if (file) {
const blob = new Blob([file], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, "image-content.txt");
}
};
</script>
</body>
</html>
Comparison of Methods
| Method | Dependencies | Browser Support | Ease of Use |
|---|---|---|---|
| Native JavaScript | None | Modern browsers | Moderate |
| FileSaver.js | External library | Excellent | Very Easy |
Conclusion
Both native JavaScript and FileSaver.js provide effective ways to create and save text files. Native JavaScript is suitable for simple use cases, while FileSaver.js offers better cross-browser compatibility and additional features for complex applications.
