Reading client side text file using Javascript

If you want to read files on the client using HTML5's FileReader, you must use Firefox, Chrome or IE 10+. If that is true, the following example reads a text file on the client.

your example attempts to use fopen that I have never heard of (on the client)

http://jsfiddle.net/k3j48zmt/

   document.getElementById('file').addEventListener('change', readFile, false);

   function readFile (evt) {
       var files = evt.target.files;
       var file = files[0];           
       var reader = new FileReader();
       reader.onload = function(event) {
         console.log(event.target.result);            
       }
       reader.readAsText(file)
    }

For IE<10 support you need to look into using an ActiveX Object like ADO.Stream Scripting.FileSystemObject http://msdn.microsoft.com/en-us/library/2z9ffy99(v=vs.85).aspx but you'll run into a security problem. If you run IE allowing all ActiveX objects (for your website), it should work.


There is such thing as HTML5 File API to access local files picked by user, without uploading them anywhere.

It is quite new feature, but supported by most of modern browsers.

I strongly recommend to check out this great article to see, how you can use it.

There is one problem with this, you can't read big files (~400 MB and larger) because straight forward FileAPI functions attempting to load entire file into memory.

If you need to read big files, or search something there, or navigate by line index check my LineNavigator, which allows you to read, navigate and search in files of any size. Try it in jsFiddle! It is super easy to use:

var navigator = new FileNavigator(file);    

navigator.readSomeLines(0, function linesReadHandler(err, index, lines, eof, progress) {    
    // Some error
    if (err) return;

    // Process this line bucket
    for (var i = 0; i < lines.length; i++) {
        var line = lines[i]; 
        // Do something with it
    }

    // End of file
    if (eof) return;

    // Continue reading
    navigator.readSomeLines(index + lines.length, linesReadHandler);
});

Well I got beat to the answer but its different:

<input type="file" id="fi" />
<button onclick="handleFile(); return false;">click</button>

function handleFile() {
    var preview = document.getElementById('prv')
    var file = document.getElementById('fi').files[0];
    var div = document.body.appendChild(document.createElement("div"));
    div.innerHTML = file.getAsText("utf-8");
}

This will work in FF 3.5 - 3.6, and that's it. FF 4 and WebKit you need to use the FileReader as mentioned by Juan Mendes.

For IE you may find a Flash solution.