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.

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

    // 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.

  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);
Answer from Useless Code on Stack Overflow
🌐
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.
🌐
SitePoint
sitepoint.com › javascript
How do I write to a local file using javascript - JavaScript - SitePoint Forums | Web Development & Design Community
February 19, 2020 - 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. Would greatly appreciate some help especially a block of code which I could use directly to do that. ... Well you can say ‘the usual security concerns are not an issue’. Javascript does not understand you.
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.

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

    // 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.

  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.
🌐
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.
🌐
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 = ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-create-and-save-text-file-in-javascript
How to Create and Save text file in JavaScript?
We have added the CDN of the ... which creates the blob object of the sentence ?This is a simple file content' and executes the ?saveAs()''function to save the text file....
Find elsewhere
🌐
Jotform
jotform.com › home › 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.
🌐
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
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
🌐
Mozilla Discourse
discourse.mozilla.org › t › how-to-save-some-string-to-file › 110754
How to save some string to file? - Development - Mozilla Discourse
February 5, 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…
Top answer
1 of 4
26

I probably would have just tacked this on as a comment to Nathaniel Johnson's answer, but I don't have the reputation yet! With regard with those methods, here are some more simple versions of his functions:

function getLocalStorage() {
    return JSON.stringify(localStorage)
}

function writeLocalStorage(data) {
    Object.keys(data).forEach(function(key) { localStorage.setItem(key, data[key])})
}
2 of 4
9

The process for saving and retrieving local storage has two parts.

First you must be able to retrieve the contents of local storage in a form that is manageable in javascript. Since local storage is a map of key-value pairs the easiest way to this is to turn local storage into a javascript object. Then take this object and turn it into a JSON string. What you do with this string is up to you but I find it easiest to just have the user copy the string into an email.

function getLocalStorage() {
    var a = {};
    for (var i = 0; i < localStorage.length; i++) {
        var k = localStorage.key(i);
        var v = localStorage.getItem(k);
        a[k] = v;
    }
    var s = JSON.stringify(a);
    return s;
}

When I get the string, I use the following function to turn my local storage into a copy of their local storage. Remember to wipe your local storage clean before duplicating their data with a call to localStorage.clear()

function writeLocalStorage(data) {
    var o = JSON.parse(data);
    for (var property in o) {
        if (o.hasOwnProperty(property)) {
            localStorage.setItem(property, o[property]);
        }
    }
}

The last part of your question is how to protect the data from overwriting. You can't write to a local file, however, you can have copy the data into <textarea> and tell the user how to copy and paste the data into a email or a more direct approach.

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

🌐
Quora
quora.com › How-can-I-write-into-the-text-file-using-JavaScript
How to write into the text file using JavaScript - Quora
Answer (1 of 4): If i understand your question, then i hope you are asking about node.js or similar ones where javascript is executed on a console or as a process in a system. If so yes, you can access via modules provided by them. For node.js, fs is a module to access file system. Node.js v8.4.0...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-write-data-in-a-text-file
JavaScript Program to write data in a text File - GeeksforGeeks
It provides a more robust solution for triggering file downloads. ... Include the FileSaver.js library in your project. Use the saveAs() function to trigger the download of the file.
Published   July 11, 2025
🌐
Code Boxx
code-boxx.com › home › 5 ways to create & save files in javascript (simple examples)
5 Ways To Create & Save Files In Javascript (Simple Examples)
May 3, 2024 - This tutorial will walk through the ways to create and save files in Javascript - Free example code download included.