0

I want to convert a csv file that is stored in my project folder to an array in javascript. I have this function:

function csvToArray (csv) {
    rows = csv.split("\n");

    return rows.map(function (row) {
        return row.split(",");
    });
};

var csv = "the,quick,brown,fox\n" +
          "jumps,over,the,lazy,dog";

var array = csvToArray(csv);

My question is when i call:

var array = csvToArray(csv);

How to make that "csv" parameter to be the path of my file that is in my project folder? For ex: cootest.csv , how do i give that file as parameter?

  • Hello , first tell me where do this function run , in the web browser of clients ?? and the file is in the server ? – Zack Heisenberg May 16 '20 at 14:21
  • You can simply pass it as a string – Deepak Terse May 16 '20 at 14:26
  • Hi, I have everything local on my pc, in the "Project" folder i have csv2array.js and cootest.csv there. And I run csv2array.js with node on my local pc in command line. How do I call it something like that "csvToArray(param) where param=the csv i have on the folder"? – Catalin Ionut May 16 '20 at 14:26
  • How I can pass it as a string? Can you show me? – Catalin Ionut May 16 '20 at 14:27
  • You'll need to open the file. If you are using a web browser, you can use this method: https://stackoverflow.com/a/61705781/3113485 – terrymorse May 16 '20 at 16:26
  • Does this answer your question? [How do I load the contents of a text file into a javascript variable?](https://stackoverflow.com/questions/196498/how-do-i-load-the-contents-of-a-text-file-into-a-javascript-variable) – michaPau May 16 '20 at 18:33

1 Answers1

0

You can just do this:

var array = csvToArray("c:/path/to/project/cootest.csv");

Kalimah
  • 11,217
  • 11
  • 43
  • 80
  • if I call it like that :var array = csvToArray("C:/Users/Catalin/Desktop/PC/Google HeatMap/cootest.csv"); I get [ [ 'C:/Users/Catalin/Desktop/PC/Google HeatMap/cootest.csv' ] ] as output, insted of lat,lng 45.652309,25.610274 49.16149,27.58405 – Catalin Ionut May 16 '20 at 15:34
  • I see. You need to use https://developer.mozilla.org/en-US/docs/Web/API/FileReader. The issue it will not load data from local desk. If you use node.js or run a local server then you can load a local file from a JS file. – Kalimah May 16 '20 at 16:59