在本地服务器上读取和parsingnode.js中的csv

我试图打开一个csv文件,我本地存储在我的节点服务器上,从我的web应用程序(和浏览器 – 用于testing目的)。

它是一个快递服务器,但是当我尝试访问/打开文件在浏览器中的威盛绝对path,我得到“无法获得文件path错误”。 林不知道为什么我不能得到的文件,当path是正确的。

文件path如下所示http://localhost:8000/files/7e911083-d12c-e5f9-10d7-db8e5e955c51.csv ,我的服务器是打开的。

我如何查看浏览器中的CSV? 更不用说从networking应用程序访问。 谢谢

快速指导将文件导入节点,然后将其parsing为json。


CSV文件示例:../THEPATHINYOURPROJECT/TOTHE/csv_FILE_YOU_WANT_TO_LOAD.csv

 ABC, 123, Fudge 532, CWE, ICECREAM 8023, POOP, DOGS 441, CHEESE, CARMEL 221, ABC, HOUSE 

1.使用以下命令安装CSV节点模块:

 npm install csv 

2.然后在你的app.js中添加下面的代码(注释只是为了解释function)

 var csv = require('csv'); // loads the csv module referenced above. var obj = csv(); // gets the csv module to access the required functionality function MyCSV(Fone, Ftwo, Fthree) { this.FieldOne = Fone; this.FieldTwo = Ftwo; this.FieldThree = Fthree; }; // Define the MyCSV object with parameterized constructor, this will be used for storing the data read from the csv into an array of MyCSV. You will need to define each field as shown above. var MyData = []; // MyData array will contain the data from the CSV file and it will be sent to the clients request over HTTP. obj.from.path('../THEPATHINYOURPROJECT/TOTHE/csv_FILE_YOU_WANT_TO_LOAD.csv').to.array(function (data) { for (var index = 0; index < data.length; index++) { MyData.push(new MyCSV(data[index][0], data[index][1], data[index][2])); } console.log(MyData); }); //Reads the CSV file from the path you specify, and the data is stored in the array we specified using callback function. This function iterates through an array and each line from the CSV file will be pushed as a record to another array called MyData , and logs the data into the console to ensure it worked. var http = require('http'); //Load the http module. var server = http.createServer(function (req, resp) { resp.writeHead(200, { 'content-type': 'application/json' }); resp.end(JSON.stringify(MyData)); }); // Create a webserver with a request listener callback. This will write the response header with the content type as json, and end the response by sending the MyData array in JSON format. server.listen(8080); // Tells the webserver to listen on port 8080(obviously this may be whatever port you want.) 

3.创build这个app.js文件后,打开一个控制台,然后input以下命令

 Node app 
  1. 这将显示以下结果

     [MYCSV {Fone:'ABC',Ftwo:'123',Fthree:'Fudge'},
        MYCSV {Fone:'532',Ftwo:'CWE',Fthree:'ICECREAM'},
        MYCSV {Fone:'8023',Ftwo:'POOP,Fthree:'DOGS'},
        MYCSV {Fone:'441',Ftwo:'CHEESE',Fthree:'CARMEL'},
        MYCSV {Fone:'221',Ftwo:'ABC',Fthree:'HOUSE'},]

5.现在,打开你的浏览器,在地址栏中input以下URL: http : //127.0.0.1 : 8080 ,你应该可以在浏览器中看到以JSON格式显示的结果。

我希望这有帮助。


如果您的应用程序完全无法访问该文件,我会首先仔细检查您的权限,并确定它位于项目的内部,并位于指定的位置。

这可能听起来很愚蠢,但是你在nodejs应用程序中路由了path? 例如在你的app.js中:

 app.get('files/*.csv',function(req,res){ //call req.url for required csv res.sendfile(PATH_TO_CSV/CSV.csv) }) 

编辑:如何浏览器select显示CSV文件,收到文件后,可能是不可预知的。 因此,parsing服务器端的csv文件可能更容易,并发送json obj而不是csv文件。