我正在尝试从Web应用程序(以及在浏览器中-用于测试目的)打开本地存储在节点服务器上的csv文件。

它是一个快递服务器,但是当我尝试通过绝对路径访问/打开浏览器中的文件时,出现“无法获取文件路径错误”。我不确定为什么路径正确时我无法获取文件。

文件路径如下所示,并且我的服务器已打开。

如何在浏览器中查看csv?更不用说从Web应用程序访问了。谢谢

最佳答案

快速说明将文件放入节点,然后解析为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中添加以下代码(这些注释仅用于解释功能)

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.创建此app.js文件后,打开一个控制台,然后键入以下命令

Node app



这将显示以下结果



    [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.现在,打开您的Web浏览器,然后在地址栏中输入以下URL:http://127.0.0.1:8080
并且您应该在浏览器中看到以JSON格式显示的结果。

我希望这有帮助。



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

10-08 16:57