Home > Software engineering >  Process a local CSV file with native JavaScript
Process a local CSV file with native JavaScript

Time:04-08

I am new to this stuff.

I'm trying to build a website about finance. I have written a scrypt in python to get shares data from an API, created my own market index and exported the datas of my index in a CSV file. It's important because, I need to create an historic and observe its evolution (the script will run automatically in a VM to add data as it goes). No problem at this stage.

Now, my purpose is to read and treat my CSV file in a JS script to stock the datas into an array (graphJS use array to display a graph and that's what I want to use).

I only found solutions that use an <input> HTML (user import a CSV on a website, I do not need that) or JSQuery (I have never been able to use it)

I'm looking for a native JavaScript solution. For the beginning, I am just looking to display datas from my CSV in console.log(). And with a "for" loop, use ".push" to iterate the datas into an array. But I will do this after I successfully displayed my file in the console.

My code does not work, can someone help me ?

const csvLocalFile = "file.csv";
    
const csv = csvLocalFile.files[0];
const reader = new FileReader();
    
reader.readAsText(csv);
    
TypeError: Cannot read properties of undefined (reading '0')

CodePudding user response:

The Issue Is That You Are Trying To Access The File Contents From A Variable Of Type String. What Your Code Does Is Try To Reference An Element Inside This String Like A Map Which doesn't Exist. Giving The Error. Also In The Code It Only Creates A New Variable whose contents are file.csv and doesn't actually store the file. To Actually Get The Contents Of Your CSV:

var filecontent
// https://stackoverflow.com/a/29176118
var openFile = function(event) {
    var input = event.target;
    var reader = new FileReader();
    reader.onload = function(){
      var text = reader.result;
      filecontent = text.replace("","")
    };
    reader.readAsText(input.files[0]);
  };

And In Your HTML

<input type="file"onchange="openFile(event)">

Your CSV Contents Will Be Stored Inside the Variable filecontent

EDIT: Non File Upload Types

let obj = await (await fetch('file.csv')).text();

This Contains Your CSV.

  • Related