Based on http://html5-demos.appspot.com/static/a.download.html: (archived)

var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();

Modified the original fiddle: http://jsfiddle.net/9av2mfjx/

Answer from Stanislav on Stack Overflow
🌐
4umi
4umi.com › web › javascript › filewrite.php
Writing to the local file system - 4umi useful Javascript
Enter the text to be saved, and optionally a name. Then click the ‘Save’ button to save the text to a local file on your system.
🌐
SitePoint
sitepoint.com › javascript
How do I write to a local file using javascript - JavaScript - SitePoint Forums | Web Development & Design Community
March 24, 2020 - Greetings to the community. Hope you’re all doing OK. I’m using javascript for programming on my own computer (not for a webpage on the net) so the usual security concerns are not an issue. How do I write to a file on my own computer? I can write and retrieve a string using local storage e.g. window.localStorage.setItem(‘games’, games) and window.localStorage.getItem(‘games’), but I’d like to be able to write strings to a file on my computer.
Discussions

jquery - How can JavaScript save to a local file? - Stack Overflow
There's already a solution for writing file JSON online but I want to save json file locally. I've tried to use this example http://jsfiddle.net/RZBbY/10/ It creates a link to download the file, us... More on stackoverflow.com
🌐 stackoverflow.com
html - Is it possible to write data to file using only JavaScript? - Stack Overflow
I want to write data to an existing file using JavaScript. I don't want to print it on console. I want to actually write data to abc.txt. I read many answered questions but everywhere they are prin... More on stackoverflow.com
🌐 stackoverflow.com
How to save some string to file?
Hello, I think it is few years I have not been trying to work with add-ons. I have the feeling like I have forgot everything. But I think I am able to inject script using JQuerry and collect some data like texts from paragraphs on a page. But still I don’t know how to save the results to ... More on discourse.mozilla.org
🌐 discourse.mozilla.org
19
0
February 6, 2023
html - Using HTML5/JavaScript to generate and save a file - Stack Overflow
I've been fiddling with WebGL lately, and have gotten a Collada reader working. Problem is it's pretty slow (Collada is a very verbose format), so I'm going to start converting files to a easier to... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Jotform
jotform.com › blog › advice › html5: filesystem api - create files and store them locally using javascript and webkit
HTML5: FileSystem API - Create Files and Store Them Locally Using JavaScript and Webkit | The Jotform Blog
April 3, 2023 - The FileSystem-API allows the creation of files and folders as well as their local storage using JavaScript. Files can be simple text files, but even more complex files such as images are possible. Modern Webkit browsers with HTML5 support are already able to handle the FileSystem-API. We show you how you can benefit from the new possibilities. ... To be able to save files and folders from inside the web browser to the local hard drive you’ll need access to the filesystem.
🌐
Envato Tuts+
code.tutsplus.com › home › coding fundamentals
How to Save a File With JavaScript | Envato Tuts+
June 19, 2022 - We create an object that contains different options for our file picker that shows up when we call the showFilePicker() method. We can suggest a name to save the file here and also pass an array of allowed file types to save.
🌐
Robkendal
robkendal.co.uk › blog › 2020-04-17-saving-text-to-client-side-file-using-vanilla-js
Saving text to a client-side file using vanilla JS - Rob Kendal
April 17, 2020 - Want to save files to the client using JavaScript? Let's look at how to save a file client-side using s simple handful of vanilla JavaScript
🌐
GitHub
gist.github.com › liabru › 11263260
Save a text file locally with a filename, by triggering a download in JavaScript · GitHub
A solution is to probably stick with manually downloading through the element appended somewhere. function appendDownloadableText(filename, string) { const data = new Blob([string]); const url = URL.createObjectURL(data); const a = ...
Find elsewhere
Top answer
1 of 11
288

You can create files in browser using Blob and URL.createObjectURL. All recent browsers support this.

You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.

Copyvar 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);

    // returns a URL you can use as a href
    return textFile;
  };

Here's an example that uses this technique to save arbitrary text from a textarea.

If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.

Copy  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');

  create.addEventListener('click', function () {
    var link = document.createElement('a');
    link.setAttribute('download', 'info.txt');
    link.href = makeTextFile(textbox.value);
    document.body.appendChild(link);

    // wait for the link to be added to the document
    window.requestAnimationFrame(function () {
      var event = new MouseEvent('click');
      link.dispatchEvent(event);
      document.body.removeChild(link);
    });

  }, false);
2 of 11
113

Some suggestions for this -

  1. If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
  2. If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
  3. To store some information on the client side that is considerably small, you can go for cookies.
  4. Using the HTML5 API for Local Storage.
🌐
TutorialsPoint
tutorialspoint.com › how-to-create-and-save-text-file-in-javascript
How to Create and Save text file in JavaScript?
October 31, 2023 - <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>
🌐
javaspring
javaspring.net › blog › how-can-javascript-save-to-a-local-file
How to Directly Save JSON Files Locally with JavaScript (No Download Link Needed) — javaspring.net
async function appendToJSON(fileHandle, newData) { // Step 1: Read existing file content const file = await fileHandle.getFile(); const existingContent = await file.text(); const existingJSON = JSON.parse(existingContent); // Step 2: Modify the data (e.g., add newData to an array) existingJSON.logs = [...existingJSON.logs, newData]; // Step 3: Write updated data back to the file const writableStream = await fileHandle.createWritable(); await writableStream.write(JSON.stringify(existingJSON, null, 2)); await writableStream.close(); } The File System Access API is designed with security in mind:
🌐
Mozilla Discourse
discourse.mozilla.org › add-ons › development
How to save some string to file? - Development - Mozilla Discourse
February 6, 2023 - Hello, I think it is few years I have not been trying to work with add-ons. I have the feeling like I have forgot everything. But I think I am able to inject script using JQuerry and collect some data like texts from par…
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-program-to-write-data-in-a-text-file
JavaScript Program to write data in a text File | GeeksforGeeks
To write data to a text file using JavaScript in a Node.js environment, the built-in fs (File System) module provides efficient file operations.
Published   January 9, 2025
Top answer
1 of 3
15

Save to filesystem

Have a look at angular-file-saver

Or use the following code as a reference in saving a BLOB. Where the blob object is generated from a JSON Object. But extration to a TEXT file is also possible.

    // export page definition to json file
    $scope.exportToFile = function(){
        var filename = 'filename'       
        var blob = new Blob([angular.toJson(object, true)], {type: 'text/plain'});
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, filename);
        } else{
            var e = document.createEvent('MouseEvents'),
            a = document.createElement('a');
            a.download = filename;
            a.href = window.URL.createObjectURL(blob);
            a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
            e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            // window.URL.revokeObjectURL(a.href); // clean the url.createObjectURL resource
        }
    }

Using LocalStorage

Saving to localStorage:

window.localStorage.setItem('key', value);

Getting from localStorage

window.localStorage.getItem('key');

Delete key from localStorage

window.localStorage.removeItem('key');

Or using the AngularJS module 'ngStorage'

Browser compatibility

Chrome - 4    
Firefox (Gecko) - 3.5    
Internet Explorer - 8    
Opera - 10.50    
Safari (WebKit) - 4

See live example (credits to @cOlz)

https://codepen.io/gMohrin/pen/YZqgQW

2 of 3
9
$http({

            method : 'GET',
            url : $scope.BASEURL + 'file-download?fileType='+$scope.selectedFile,
            responseType: 'arraybuffer',
            headers : {
                'Content-Type' : 'application/json'
            }

        }).success(function(data, status, headers, config) {
            // TODO when WS success
            var file = new Blob([ data ], {
                type : 'application/json'
            });
            //trick to download store a file having its URL
            var fileURL = URL.createObjectURL(file);
            var a         = document.createElement('a');
            a.href        = fileURL; 
            a.target      = '_blank';
            a.download    = $scope.selectedFile+'.json';
            document.body.appendChild(a);
            a.click();

        }).error(function(data, status, headers, config) {

        });

In success part need to open local system, by which the user can choose, where to save file. Here I have used <a>. And I am hitting restful service

🌐
freeCodeCamp
forum.freecodecamp.org › javascript
JavaScript code to create and save a file to my device internal storage - JavaScript - The freeCodeCamp Forum
October 28, 2019 - Hello guys, I am working on a simple html,css and JavaScript editor with a compiler. I need help how to create file with JavaScript at a button click. Something like this code <! Doctype html> <html> <body> <textarea …
🌐
Our Code World
ourcodeworld.com › articles › read › 189 › how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
How to create a file and generate a download with Javascript in the Browser (without a server) | Our Code World
May 12, 2019 - If you need to save really large files bigger then the blob's size limitation or don't have enough RAM, then have a look at the more advanced StreamSaver.js that can save data directly to the hard drive asynchronously with the power of the new streams API.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-save-data-in-local-storage-in-javascript
How to Save Data in Local Storage in JavaScript? | GeeksforGeeks
October 14, 2024 - We will use the localStorage object in JavaScript to save user input data locally in the browser.