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

How do I write to a local file using javascript - JavaScript - SitePoint Forums | Web Development & Design Community
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 ... More on sitepoint.com
🌐 sitepoint.com
0
March 24, 2020
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
javascript - save restore local storage to a local file - Stack Overflow
Is there a way to easily save and restore the local storage to a file in jquery or JavaScript? There are 3 scenarios for this: testing with a specific local storage making a backup of the local s... More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to use js to save the content in the browser to local? - Stack Overflow
I'd like to generate a txt file using Javascript whose contents would be a String and link to it to a button so that the button click would generate the file download. The file cannot be stored any... 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 | 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 - Rob Kendal
April 17, 2020 - Sure, there are lots of means available to save something to the local machine of a user, but they tend to involve either less-than-ideal solutions such as a browser's local storage, a cookie, or even using the HTML canvas blob .
🌐
SitePoint
sitepoint.com › javascript
How do I write to a local file using javascript - JavaScript - SitePoint Forums | Web Development & Design Community
March 24, 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
289

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.
Top answer
1 of 4
27

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.

Find elsewhere
🌐
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?
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>
🌐
Envato Tuts+
code.tutsplus.com › home › coding fundamentals
How to Save a File With JavaScript | Envato Tuts+ - Code
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.
🌐
Reddit
reddit.com › r/learnjavascript › how can i save a json value from html/javascript in a json file locally?
r/learnjavascript on Reddit: How can I save a json value from HTML/JavaScript in a json file locally?
December 29, 2021 -

I want to save some numbers from a small program in a local JSON file.

Example:

const increaseButton = document.getElementById("increase-button")
const numberField = document.getElementById("count-field")
let myNum = 0
let myArray = []
increaseButton.addEventListener("click", increaseNum)

function increaseNum() {
    myNum++
    numberField.innerText = myNum
    myArray.pop()
    myArray.push(myNum)
    let jsonString = JSON.stringify(Object.assign({}, myArray))
    console.log(jsonString)
}

The jsonString should be saved in a local file "myjson.json".

Goal: If I increase the number with the increaseButton, the new value should be saved in the "myjson.json" file:

{
    "numbers": {
        "0":1}
}

The only option I found was with node.js plugin "fs" and a lot of code. Couldn't it be easier?

Top answer
1 of 1
2

You can't just access the Filesystem from your browser. Your options depend on what you are trying to achieve.

1. Save a txt file on the users local filesystem

You can create a "downloadable" element directly from JS. Depending on the browser the user will be prompted to allow downloads and/or where to store the file. You cannot access the file afterwards.

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

Source: https://www.codegrepper.com/code-examples/javascript/javascript+download+text+as+txt+file

2. Save data inside the browser so you can read/write whenever the users visits your website

The localstorage API can create small keyed objects (like 5-10 mb) on the user system. You can read/write anything to or from it that is serializable.

localStorage.setItem('myCat', 'Tom');
const cat = localStorage.getItem('myCat');
localStorage.removeItem('myCat');

Here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

3. Save a file/data on your server

If you need the file on the server itself, you must create a backend with php, nodejs etc. Then you must implement an endpoint that accepts the data you want to save and inside nodejs you can import the "fs" and directly write files to it.

const fs = require('fs')

const content = 'Some content!'

fs.writeFile('/Users/joe/test.txt', content, err => {
  if (err) {
    console.error(err)
    return
  }
  //file written successfully
})

Source: https://nodejs.dev/learn/writing-files-with-nodejs

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › 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.
🌐
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
🌐
xjavascript
xjavascript.com › blog › save-html-locally-with-javascript
Can You Save HTML Locally with JavaScript via file:// URL? (No Server Needed) — xjavascript.com
Browsers enforce strict security policies for file:// URLs to prevent malicious scripts from accessing or modifying your local files without permission. Key restrictions include: No Arbitrary File Writes: JavaScript cannot write to arbitrary locations on your filesystem (e.g., overwriting C:\Windows\System32 files).
🌐
Newfivefour
newfivefour.com › javascript-save-text-string-as-local-file.html
Loading...
So CSS grid lets align your divs in grids. It's more visual and slightly less confusing than flexbox but needs more css -- harder to quickly hack · Our grid will have a top spanning header, an image under the header to the left and a text area to the right of the image · But we want to centre ...