How can I read a local file with Papa Parse?

无人久伴 提交于 2020-01-21 03:14:29

问题


How can I read a local file with Papa Parse? I have a file locally called challanges.csv, but after many tried I can't parse it with Papa Parse.

var data;

Papa.parse('challanges.csv', {
  header: true,
  dynamicTyping: true,
  complete: function(results) {
    console.log(results);
    data = results.data;
  }
});

As far as I know, I'm having problems with opening the csv file as File. How can I do it with javascript?


回答1:


The File API suggested by papaparse's docs is meant for browser used. Assuming that you are running this on node at server side, what works for me is leveraging the readable stream:

const fs = require('fs');
const papa = require('papaparse');
const file = fs.createReadStream('challenge.csv');
var count = 0; // cache the running count
papa.parse(file, {
    worker: true, // Don't bog down the main thread if its a big file
    step: function(result) {
        // do stuff with result
    },
    complete: function(results, file) {
        console.log('parsing complete read', count, 'records.'); 
    }
});

There may be an easier interface, but so far this works quite well and offer the option of streaming for processing large files.




回答2:


You need to add one more line in your config: download: true,.

var data;

Papa.parse('../challanges.csv', {
  header: true,
  download: true,
  dynamicTyping: true,
  complete: function(results) {
    console.log(results);
    data = results.data;
  }
});

Update: with this answer you dont need a FILE OBject. You can pass the filename and papa parse will "download" it.




回答3:


This is to reiterate that the best answer is Murat Seker's.

All that is necessary is to add the to the config download: true and the local path will be downloaded by Papa Parse. The streaming answer by Philip M. is not the best answer.

var data;

Papa.parse('challanges.csv', {
  header: true,
  download: true,
  dynamicTyping: true,
  complete: function(results) {
    console.log(results);
    data = results.data;
  }
});

P.S. I do not have enough reputation to comment on Murat Seker's answer. So, I reposted an answer. Any love towards reputation will be appreciated. :-)



来源:https://stackoverflow.com/questions/49752889/how-can-i-read-a-local-file-with-papa-parse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!