How to read csv file in node js
我正在尝试使用节点js读取csv文件。
她是我的密码
1 2 3 4 5 6 | fs.readFile(config.csvUploadPath, function read(err, data) { if (err) { throw err; } console.log(data + 'my data') }); |
安慰:
1 2 3 4 | ID D11 D33 D55 |
在这里,我想获取列ID中的元素并将其存储在数组中。 我怎样才能做到这一点? 谁能建议我帮忙。 谢谢。
我的控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var partnersModel = new partners(params); fs.readFile(config.csvUploadPath, function read(err, data) { if (err) { throw err; } dataArray = data.toString().split(/ ? /); dataArray.forEach(function(v,i){ if(v !== 'DUI'){ partnersModel.dui.push(v); } }); }); partnersModel.save(function(error, response){ |
使用库,CSV有很多陷阱。 我来享受包
1 2 3 4 5 6 7 | const fs = require('fs') var parse = require('csv-parse') fs.readFile(inputPath, function (err, fileData) { parse(fileData, {columns: false, trim: true}, function(err, rows) { // Your CSV data is in an array of arrys passed to this callback as rows. }) }) |
由于您的文件每行没有多个值,并且除了换行符外不包含定界符,因此它只是CSV。
1 2 3 4 5 6 7 8 9 | const fs = require('fs') fs.readFile(inputPath, 'utf8', function (err, data) { var dataArray = data.split(/ ? /); //Be careful if you are in a world... // Your array contains ['ID', 'D11', ... ] }) |
我在此答案中使用了流,
1 2 3 4 5 6 7 8 9 10 11 12 13 | const parse = require('csv-parse') const fs = require('fs') const data = [] fs.createReadStream(filename) .pipe(parse({ delimiter: ',' })) .on('data', (r) => { console.log(r); data.push(r); }) .on('end', () => { console.log(data); }) |
从如何使用javascript?从* .CSV文件读取数据,请使用jQuery-CSV库。
Note: The library is designed to handle any CSV data that is RFC 4180 compliant, including all of the nasty edge cases that most 'simple' solutions overlook.
1 2 3 4 5 6 7 8 9 10 11 12 | var fs = require('fs'); var $ = jQuery = require('jquery'); $.csv = require('jquery-csv'); var sample = './path/to/data/sample.csv'; fs.readFile(sample, 'UTF-8', function(err, csv) { $.csv.toArrays(csv, {}, function(err, data) { for(var i=0, len=data.length; i<len; i++) { console.log(data[i]); //Will print every csv line as a newline } }); }); |
来自