How to read csv file in node js

人盡茶涼 提交于 2019-12-01 15:56:18
trognanders

Use a library, CSV has lots of gotchas. I have come to enjoy the package csv. It is located here: https://www.npmjs.com/package/csv . Here is a very quick example using the async api.

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.
  })
})

Since your file does not have multiple values per row and contains no delimiters besides newline, it is only trivially CSV. Maybe String.prototype.split() is for you?

const fs = require('fs')
fs.readFile(inputPath, 'utf8', function (err, data) {
  var dataArray = data.split(/\r?\n/);  //Be careful if you are in a \r\n world...
  // Your array contains ['ID', 'D11', ... ]
})
zelusp

From How to read data From *.CSV file using javascript?, use the jQuery-CSV library.

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.

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
    }
  });
});

code snippet from jquery-csv's examples here.

I used a stream, fs, and csv-parse like in this answer:

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);
  })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!