[javascript] How to read and write into file using JavaScript?

Can anybody give some sample code to read and write a file using JavaScript?

This question is related to javascript file-io

The answer is


If you are using JScript (Microsoft's Javascript) to do local scripting using WSH (NOT in a browser!) you can use Scripting.FileSystemObject to access the file system.

I think you can access that same object in IE if you turn a lot of security settings off, but that would be a very, very bad idea.

MSDN here


No. Browser-side javascript doesn't have permission to write to the client machine without a lot of security options having to be disabled


You'll have to turn to Flash, Java or Silverlight. In the case of Silverlight, you'll be looking at Isolated Storage. That will get you write to files in your own playground on the users disk. It won't let you write outside of your playground though.


The future is here! The proposals are closer to completion, no more ActiveX or flash or java. Now we can use:

You could use the Drag/Drop to get the file into the browser, or a simple upload control. Once the user has selected a file, you can read it w/ Javascript: http://www.html5rocks.com/en/tutorials/file/dndfiles/


From a ReactJS test, the following code successfully writes a file:

import writeJsonFile from 'write-json-file';

const ans = 42;
writeJsonFile('answer.txt', ans);

const json = {"answer": ans};
writeJsonFile('answer_json.txt', json);

The file is written to the directory containing the tests, so writing to an actual JSON file '*.json' creates a loop!


Here is write solution for chrome v52+ (user still need to select a destination doe...)
source: StreamSaver.js

<!-- load StreamSaver.js before streams polyfill to detect support -->
<script src="StreamSaver.js"></script>
<script src="https://wzrd.in/standalone/web-streams-polyfill@latest"></script>
const writeStream = streamSaver.createWriteStream('filename.txt')
const encoder = new TextEncoder
let data = 'a'.repeat(1024)
let uint8array = encoder.encode(data + "\n\n")

writeStream.write(uint8array) // must be uInt8array
writeStream.close()

Best suited for writing large data generated on client side.
Otherwise I suggest using FileSaver.js to save Blob/Files


In the context of browser, Javascript can READ user-specified file. See Eric Bidelman's blog for detail about reading file using File API. However, it is not possible for browser-based Javascript to WRITE the file system of local computer without disabling some security settings because it is regarded as a security threat for any website to change your local file system arbitrarily.

Saying that, there are some ways to work around it depending what you are trying to do:

  1. If it is your own site, you can embed a Java Applet in the web page. However, the visitor has to install Java on local machine and will be alerted about the security risk. The visitor has to allow the applet to be loaded. An Java Applet is like an executable software that has complete access to the local computer.

  2. Chrome supports a file system which is a sandboxed portion of the local file system. See this page for details. This provides possibly for you to temporarily save things locally. However, this is not supported by other browsers.

  3. If you are not limited to browser, Node.js has a complete file system interface. See here for its file system documentation. Note that Node.js can run not only on servers, but also any client computer including windows. The javascript test runner Karma is based on Node.js. If you just like to program in javascript on the local computer, this is an option.


This Javascript function presents a complete "Save As" Dialog box to the user who runs this through the browser. The user presses OK and the file is saved.

Edit: The following code only works with IE Browser since Firefox and Chrome have considered this code a security problem and has blocked it from working.

// content is the data you'll write to file<br/>
// filename is the filename<br/>
// what I did is use iFrame as a buffer, fill it up with text
function save_content_to_file(content, filename)
{
    var dlg = false;
    with(document){
     ir=createElement('iframe');
     ir.id='ifr';
     ir.location='about.blank';
     ir.style.display='none';
     body.appendChild(ir);
      with(getElementById('ifr').contentWindow.document){
           open("text/plain", "replace");
           charset = "utf-8";
           write(content);
           close();
           document.charset = "utf-8";
           dlg = execCommand('SaveAs', false, filename+'.txt');
       }
       body.removeChild(ir);
     }
    return dlg;
}

Invoke the function:

save_content_to_file("Hello", "C:\\test");

You cannot do file i/o on the client side using javascript as that would be a security risk. You'd either have to get them to download and run an exe, or if the file is on your server, use AJAX and a server-side language such as PHP to do the i/o on serverside


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 files, but that is it unfortunately.

If you are looking to save user information, you will most likely need to use cookies.


For completeness, the OP does not state he is looking to do this in a browser (if he is, as has been stated, it is generally not possible)

However javascript per se does allow this; it can be done with server side javascript.

See this documentation on the Javascript File class

Edit: That link was to the Sun docs that now have been moved by Oracle.

To keep up with the times here's the node.js documentation for the FileSystem class: http://nodejs.org/docs/latest/api/fs.html

Edit(2): You can read files client side now with HTML5: http://www.html5rocks.com/en/tutorials/file/dndfiles/


There are two ways to read and write a file using JavaScript

  1. Using JavaScript extensions

  2. Using a web page and Active X objects


For Firefox:

var file = Components.classes["@mozilla.org/file/local;1"].
       createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home");

See https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O

For others, check out the TiddlyWiki app to see how it does it.


Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.

const data = {name: 'Ronn', age: 27};              //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile';                     //filename to download
a.click();

Check Blob documentation here - Blob MDN


Currently, files can be written and read from the context of a browser tab/window with the File, FileWriter, and FileSystem APIs, though there are caveats to their use (see tail of this answer).

But to answer your question:

Using BakedGoods*

Write file:

bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

Read file:

bakedGoods.get({
        data: ["testFile"],
        storageTypes: ["fileSystem"],
        options: {fileSystem:{storageType: Window.PERSISTENT}},
        complete: function(resultDataObj, byStorageTypeErrorObj){}
});

Using the raw File, FileWriter, and FileSystem APIs

Write file:

function onQuotaRequestSuccess(grantedQuota)
{

    function saveFile(directoryEntry)
    {

        function createFileWriter(fileEntry)
        {

            function write(fileWriter)
            {
                var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
                fileWriter.write(dataBlob);              
            }

            fileEntry.createWriter(write);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: true, exclusive: true},
            createFileWriter
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Read file:

function onQuotaRequestSuccess(grantedQuota)
{

    function getfile(directoryEntry)
    {

        function readFile(fileEntry)
        {

            function read(file)
            {
                var fileReader = new FileReader();

                fileReader.onload = function(){var fileData = fileReader.result};
                fileReader.readAsText(file);             
            }

            fileEntry.file(read);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: false},
            readFile
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Just what you asked for right? Maybe, maybe not. The latter two of the APIs:

  • Are currently only implemented in Chromium-based browsers (Chrome & Opera)
  • Have been taken off the W3C standards track, and as of now are proprietary APIs
  • May be removed from the implementing browsers in the future
  • Constrict the creation of files to a sandbox (a location outside of which the files can produce no effect) on disk

Additionally, the FileSystem spec defines no guidelines on how directory structures are to appear on disk. In Chromium-based browsers for example, the sandbox has a virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser), within which the directories and files created with the APIs are placed.

So though you may be able to write files to a system with the APIs, locating the files without the APIs (well, without the FileSystem API) could be a non-trivial affair.

If you can deal with these issues/limitations, these APIs are pretty much the only native way to do what you've asked.

If you're open to non-native solutions, Silverlight also allows for file i/o from a tab/window contest through IsolatedStorage. However, managed code is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.

Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :

//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
    data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
    storageTypes: ["fileSystem", "silverlight"],
    options: {fileSystem:{storageType: Window.PERSISTENT}},
    complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});

* BakedGoods is a Javascript library that establishes a uniform interface that can be used to conduct common storage operations in all native, and some non-native storage facilities. It is maintained by this guy right here : ) .


here's the mozilla proposal

http://www-archive.mozilla.org/js/js-file-object.html

this is implemented with a compilation switch in spidermonkey, and also in adobe's extendscript. Additionally (I think) you get the File object in firefox extensions.

rhino has a (rather rudementary) readFile function https://developer.mozilla.org/en/Rhino_Shell

for more complex file operations in rhino, you can use java.io.File methods.

you won't get any of this stuff in the browser though. For similar functionality in a browser you can use the SQL database functions from HTML5, clientside persistence, cookies, and flash storage objects.


To create file try

function makefile(){
  var fso;
  var thefile;

    fso = new ActiveXObject("Scripting.FileSystemObject");
    thefile=fso.CreateTextFile("C:\\tmp\\MyFile.txt",true);

    thefile.close()
    }

Create your directory in the C drive because windows has security against writing from web e.g create folder named "tmp" in C drive.