2015-01-14 58 views
4

我想解析一個.csv文件,該文件將位於使用JavaScript中Papa Parse的已知本地目錄中。如果我有一個機制來要求用戶瀏覽文件,它就像一個魅力。但我無法弄清楚如何讓它在給定的位置自動訪問文件。我覺得我缺少一些簡單的東西,但我不確定是什麼。到目前爲止我的代碼:無法使用Papa Parse對CSV解析進行硬編碼的文件目錄

<html> 
<head> 
    <title>testing papa parse</title> 
</head> 
<body> 

<script src="js/PapaParse-4.0.7/papaparse.min.js"></script> 
<script src="js/jquery-2.1.1.min.js"></script> 
<script> 
    var data; 
    // var file = evt.target.files[0]; 
    var file = "\\files\\telemetryData.csv"; 

     Papa.parse(file, { 
     //makes sure the first line is interpreted as a header, not data 
     header: true, 

     //allows stuff to be typed as their respective primitive types instead of only strings. turned off in this case 
     dynamicTyping: false, 

     //allows you to define the delimiter if not a default comma 
     delimiter: ",", 

     //allows you to define a comment line, which would be skipped by the parser 
     comments: "//", 

     //turns on fastmode, quicker but assumes no quoted fields is present 
     fastmode: true, 

     download: true, 

     step: function(results){ 
     console.log(results.data); 
     } 
    }); 
</script> 

</body> 
</html> 

CSV數據:

TEAM_ID,MISSION_TIME,ALT_SENSOR,OUTSIDE_TEMP,INSIDE_TEMP,VOLTAGE,FSW_STATE 
ubArtemis,0,36,20,20,9,1 
ubArtemis,1,45,18,20,9,1 
ubArtemis,2,50,16,20,9,1 
ubArtemis,3,65,14,19,9,1 
ubArtemis,4,79,12,17,8,2 
//hello this is a comment 
ubArtemis,5,100,10,16,8,3 
ubArtemis,6,120,8,15,8,4 
ubArtemis,7,145,6,14,8,5 
ubArtemis,8,160,4,12,7,6 
ubArtemis,9,200,2,10,6,7 
+0

你不能這樣做,理由很充分。如果任何網站上的腳本可以隨意訪問任何訪問者的計算機上的任何文件,那將是非常糟糕的。 –

+0

我明白了。會有解決方法嗎? – YazanLpizra

+0

是的,用戶必須從一個''元素中選擇它,否則你必須通過傳遞一個URL來下載它。 – Matt

回答

4

使用jQuery 「得到」 的文件內容,並使用papaparse解析CSV字符串:

//parse the data file 
    var csvfile = "data/data.csv"; 

    $.get(csvfile, function (data) { 
     var csvdata = Papa.parse(data); 
     console.log(csvdata); 
    }); 
0

你需要在使用它進行解析之前,從文件中讀取數據。下面的代碼適用於我

Papa.parse(fs.createReadStream(file), { 
     delimiter: ",", 
     header: true, 
     complete: function(results) { 
      console.log("Finished:", results.data); 
      done(); 
     } 
    }); 
相關問題