I am new to javascript . all codes available on the internet related to create text file using javascript is not working in my laptop. can anybody give me idea or with possible code.
Asked
Active
Viewed 5.4k times
10
-
possible duplicate of [javascript code to save a txt file](http://stackoverflow.com/questions/6854296/javascript-code-to-save-a-txt-file) – Trevi Awater Jun 25 '15 at 10:50
-
2You should define "is not working". Maybe your browser is too old? Some of the examples use fairly new techniques. – Sirko Jun 25 '15 at 10:50
2 Answers
8
This code should work, give this a try and if this doesn't work then it may be an issue with your browser:
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
And the HTML:
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button>
<a download="info.txt" id="downloadlink" style="display: none">Download</a>
Taken from this Fiddle:

n00dl3
- 21,213
- 7
- 66
- 76

Web Develop Wolf
- 5,996
- 12
- 52
- 101
-
-
It works in Firefox 38 and Chrome 43, but not IE10/11. The text file is generated and can be saved by right click > save as, but the listener for the download link doesn't work. I can't find an example that works in IE. – Equalsk Jun 26 '15 at 08:44
3
A very fast and easy solution is to use FileSaver.js :
https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js
Then it takes only 2 lines of code to download a txt file :
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
This code example will display a dialog box to download a file named "hello world.txt" containing the text "Hello, world!". Just replace this by the file name and the text content of your choice !

Ismael EL ATIFI
- 1,939
- 20
- 16