4

There are plenty of examples of reading a CSV file using jQuery however javascript examples are few and far between.

As i am using an internal script editor for a particular application, i am limited to using Javascript only.

I have a csv file that has headings followed by data in each row.

Heading1,Heading2,Heading3,Heading4
row1data1,row1data2,row1data3,row1data4
row2data1,row2data2,row2data3,row2data4

The delimiter being used is , however there could be others e.g. ^.

As i can't upload a file, i have the option to manually reference an absolute path.

Is there a way i can use only javascript to read a csv file?

PeanutsMonkey
  • 6,919
  • 23
  • 73
  • 103
  • 1
    Are you asking how to read a file with javascript? Or how to parse a large string you have in javascript as CSV? – Alex Wayne Feb 26 '14 at 04:26
  • You can fetch the csv using ajax/text and then split it with newline, then comma – SajithNair Feb 26 '14 at 04:27
  • @Sajith Nair - I can't use AJAX. I am limited to simple ol' javascript – PeanutsMonkey Feb 26 '14 at 04:30
  • @Alex Wayne - I am asking to read the contents of a file with javascript and place its contents into an key value array. – PeanutsMonkey Feb 26 '14 at 04:31
  • @PeanutsMonkey Those are two questions with two very different answers. Maybe you should ask two questions instead? – Alex Wayne Feb 26 '14 at 04:45
  • @Alex Wayne - There are part of the same problem though. If the general consensus is to split the questions i will. – PeanutsMonkey Feb 26 '14 at 04:48
  • Possible duplicate: [http://stackoverflow.com/questions/11951534/reading-csv-file-into-javascript-string-or-array](http://stackoverflow.com/questions/11951534/reading-csv-file-into-javascript-string-or-array) – Ahsan Khurshid Feb 26 '14 at 05:11
  • I think this is the best possible duplicate:[http://stackoverflow.com/questions/7431268/how-read-data-from-csv-file-using-javascript](http://stackoverflow.com/questions/7431268/how-read-data-from-csv-file-using-javascript) – Ahsan Khurshid Feb 26 '14 at 05:13
  • 1
    @A.K - If you have a look at the 2 posts you cited, they either use PHP, jQuery or AJAX neither of which i can use. – PeanutsMonkey Feb 26 '14 at 18:38

1 Answers1

15

As a start, here is a couple of ways to read a file with javascript

HttpRequest: (from web server or absolute path)

Source: Javascript - read local text file

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

And specify file:// in your filename when using an absolute path

readTextFile("file:///C:/your/path/to/file.txt");

FileReader API:

Source:
- http://codepen.io/matt-west/pen/KjEHg
- http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api

HTML

<div id="page-wrapper">

    <h1>Text File Reader</h1>
    <div>
        Select a text file: 
        <input type="file" id="fileInput">
    </div>
    <pre id="fileDisplayArea"><pre>

</div>

JS

window.onload = function() {
    var fileInput = document.getElementById('fileInput');
    var fileDisplayArea = document.getElementById('fileDisplayArea');

    fileInput.addEventListener('change', function(e) {
        var file = fileInput.files[0];
        var textType = /text.*/;

        if (file.type.match(textType)) {
            var reader = new FileReader();

            reader.onload = function(e) {
                fileDisplayArea.innerText = reader.result;
            }

            reader.readAsText(file);    
        } else {
            fileDisplayArea.innerText = "File not supported!"
        }
    });
}

JS on MS Windows (simple sample)

Source: http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx

function ReadFiles()
{
   var fso, f1, ts, s;
   var ForReading = 1;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   s = ts.ReadLine();
   // s holds the text content
   ts.Close();
}
Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165
  • 1
    @PellePenna - Sorry PellePenna. The application doesn't support XMLHTTPRequest or a combination of HTML & JS. It needs to be straight-out javascript. – PeanutsMonkey Feb 26 '14 at 18:38
  • I updated my answer, at bottom, how to use it on a Windows computer. You have to test if UNC path will work. If not, you have to assing a letter to a path, which of course can be done to both ip and local network computers – Asons Feb 26 '14 at 18:53
  • @PellePenna - Thanks PellePenna. The last example you gave worked like a charm – PeanutsMonkey Mar 03 '14 at 18:10
  • 1
    Useful for reading many files, like html and txt, but using a csv brings up "File not supported!"... Question referred to csv in particular. Am I right or did I miss something? – Patrick Keane Jul 31 '14 at 13:50
  • All "text" files should but binary likely not (haven't tried though), so make sure it's a text file. – Asons Jul 31 '14 at 18:39
  • @PatrickKeane And btw, you can change which file types to support (2:nd sample above), by adding them at the line `if (file.type.match(textType))`. – Asons Aug 02 '14 at 06:37