快速指示要將文件放入節點,然後將其解析爲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.現在,打開您的瀏覽器並在地址欄中輸入以下URL:http://127.0.0.1:8080 並且您應該在瀏覽器中以JSON格式顯示結果。
我希望這會有所幫助。
如果你的應用程序是完全無法訪問該文件,我會先仔細檢查您的權限,這是該項目的內部,並在指定的位置。
你沒有提供任何服務器代碼,如果你想獲得關於SO的準確幫助,你應該。隨時提供代碼。 – peteb