3

I'm trying to do something that I think is fairly simple, but doesn't seem to be working. I have a .csv file in the same directory as my script file. I want to create an object or an array using the data from the .csv file. How do I access the local file using javascript?

Sorry for the lack of code, but I don't even know which route to go down; I've tried .get and ajax and this plugin but I just don't know what I'm doing. Could someone give me a clear example of how to load the file and print it in a div?

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
  • same directory on server or on client machine? If you want to open client files you will need to use the fileReader api (https://developer.mozilla.org/en-US/docs/Web/API/FileReader). If you are doing it server side, it depends on what you are running. – Jonah Williams Nov 01 '15 at 22:34
  • It would be on the sever. That said, in my testing process, my file structure is just on my desktop - I'm not running it as a server. –  Nov 01 '15 at 22:39
  • Well, that have to be one or the other. APIs are different for fetching a file with a file (file://) or HTTP (http://) protocol. – sergeyz Nov 01 '15 at 22:44

2 Answers2

1

PapaParse() does an excellent job here, for example this will do the job for you:

Papa.parse(file, {
    complete: function(results) {
        console.log("Finished:", results.data);
    }
});

DEMO

baao
  • 71,625
  • 17
  • 143
  • 203
1

In order to simulate a static file server, you can run an http server using python on the command line. This is necessary to use ajax requests.

python -m SimpleHTTPServer  

Or if you have python 3

python -m http.server

Now there are two parts to getting that file to a webpage. 1) make an ajax request, 2) parse the csv. There are many different libraries that implement ajax requests, but in this case you might find the easiest out of the box solution which combines both is d3.js.

d3.csv("filename.csv", function(err, data) {

    // csv is parsed into an array of objects, as data

});

Of course this will only work if you are loading your page from localhost.

EDIT:

Make sure you run your http server from the location of your index.html file. then the request you make in the d3.csv function is relative to index. finally, the data is only available inside the callback, and any error message (or null) will be put inside the err argument.

Project
|
+-- index.html
|    
+-- data
|  |  
|  \-- dataset.csv

Then the code in index.html would look like

d3.csv("data/dataset.csv", function(err, data) {

    if (err) console.log(err) // error messages

    console.log(data);   // should contain the parsed csv
});
Jonah Williams
  • 20,499
  • 6
  • 65
  • 53