简体   繁体   中英

Using JavaScript to load data from CSV file into the script as array

I am working on an Adobe Illustrator JavaScript and need to load data from a CSV file on my computer as an array into the script so I can work with them later (everything Is happening on my computer, and nothing happens online/web browser.) I need every line of the text in the CSV to be separated in the array, and then I need to separate the words in the line into an array so that I have an array of arrays in the end. Each line has three variables which get fed into a function that has to happen for each line.

The error I am getting from the code below says:

'Error 25: Expected:;. -> let reader = new FileReader();'

  var csv = Folder ("Path to my csv file");
  function processData(csvFile) {
      let reader = new FileReader();
      reader.readAsText(csvFile);
      reader.onload = function(event) {
        var allText = reader.result;
      };
      const allTextLinesArr = allText.toString().split(/\r\n|\n/);
      var alen = allTextLinesArr.length;
      const allTextLinesArrArr = [];

      for (var i=1; i<=alen; i++) {
        allTextLinesArrArr[i-1] = allTextLinesArr[i-1].split(",");
        }

      for (var i=1; i<=alen; i++) {
        doStuff(allTextLinesArrArr[i-1][0],allTextLinesArrArr[i-1][1],allTextLinesArrArr[i-1][2]);
        }

  }

Error 25 isn't a standard Javascript error that you'd ever see in a web browser.

Are you using something like Adobe ExtendScript perhaps? If so, perhaps update your question with exactly where this code is being used.

The answer however, is probably that the program that you're using has an old version of Javascript that doesn't support FileReader (which is a fairly new bit of Javascript code).

It's also worth noting that you wouldn't usually be able to access the user's file from Javascript (without the user selecting it manually). However, it's possible that the program you're using to run JS does support this.

Here is the classic native Extendscript way to read CSV data from a file:

var csv_file = File('test.csv');
csv_file.open('r');
csv_file.encoding = 'utf-8';
var data = csv_file.read().split('/\r\n|\n/'); // split by lines
csv_file.close();
for (var row in data) data[row].split(','); // split all lines by comas

alert(data); // here is your 2d array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM