Search code examples
javascripthtmlfileapilocal-files

File manipulations such as Read/Write local files using Javascript without server


I'm just trying on the task, file manipulation system using java script. As I was referred from W3C File API( https://www.w3.org/TR/FileAPI/ ), we can only read local files like

var file = "test.txt";
function readTextFile(file) {
   var readFile;    
   if(window.XMLHttpRequest){
      // for new browsers
      readFile = new XMLHttpRequest();
   }else{
      //for old browsers like IE5 or IE6
      readFile = new ActiveXObject("Microsoft.XMLHTTP");
   }    
   readFile.open("GET", file, true);
   readFile.onreadystatechange = function() {
      if(readFile.readyState === 4) {
         if(readFile.status === 200 || readFile.status == 0) {
            //text will be displayed that read from the file
            console.log(readFile.responseText);
         }
      }
   }
   readFile.send(null);
}

but it looks there is no options to write on file without server. I was tried to fetch solutions from the websites like http://www.stackoverflow.com/, the study says almost there is no possibilities.

For an example what I got is

from https://gist.github.com/Arahnoid/9925725

It shows error "TypeError: file.open is not a function."

So my question is, Is there any possible to file manipulations(asking only about Write file) for local files without using server-side scripting or is any extensions like available?

We can do file manipulations using server scripting languages such as PHP, Node.js.

Thanks in advance.


Solution

  • In your code, it's not reading from the local file (test.txt), it's sending Ajax GET request to server and read file in server side.

    To read local file (files that stored in machine where browser is installed), you need to use FileAPI, which is not used in current code.

    To write file to local, it's impossible to write it directly using JavaScript. Otherwise, it would be a huge security vulnerability. However, you can generate a URL from File object, and use that URL as the href attribute of <a> tag, so that user can download and "write to local" manually.

    Here is a code snippet to read & "write" local file:

    var inputElement = document.getElementById("input");
    var reader = new FileReader();
    var downloadLink = document.getElementById('downloadLink');
    
    reader.onloadend = function(){
      console.log(reader.result);
    }
    inputElement.addEventListener("change", handleFiles, false);
    function handleFiles() {
      var fileSelected = this.files[0]; /* now you can work with the file list */
      reader.readAsBinaryString(fileSelected);
      downloadLink.href = window.URL.createObjectURL(fileSelected);
    }
    <input type="file" id="input">
    <a id="downloadLink" download>Download</a>