How to read csv file in node js

I am trying to read a csv file using node js. This is my code.

fs.readFile(config.csvUploadPath, function read(err, data) {
    if (err) {
        throw err;
    }
    console.log(data + 'my data')
});

CONSOLE:

ID
D11
D33
D55

Here I want to get the elements in the column id and store them in an array. How can i do this? Can anyone offer me help. Thank you My controller:

var partnersModel = new partners(params);
        fs.readFile(config.csvUploadPath, function read(err, data) {
            if (err) {
                throw err;
            }
        dataArray = data.toString().split(/\r?\n/);
            dataArray.forEach(function(v,i){
                if(v !== 'DUI'){
                  partnersModel.dui.push(v);
                }
            });
        });
        partnersModel.save(function(error, response){
+9
source share
3 answers

Use the library, CSV has many errors. I came to enjoy the package csv. It is here: https://www.npmjs.com/package/csv . Here is a very quick example using 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.
  })
})

, , CSV. , String.prototype.split() ?

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', ... ]
})
+18

*.CSV javascript? jQuery-CSV.

. CSV-, RFC 4180, , "" .

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

jquery-csv .

0

, fs csv-parse, :

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

Source: https://habr.com/ru/post/1014277/


All Articles