Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read csv file in node js

Tags:

I am trying to read a csv file using node js. Her 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 those in an array. How can I do that? Can anyone suggest me help. Thanks. 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){ 
like image 350
MMR Avatar asked Jan 21 '17 07:01

MMR


People also ask

How do you write data in a CSV file using node JS?

Using the fast-csv Module const fastcsv = require('fast-csv'); const fs = require('fs'); const ws = fs. createWriteStream("out. csv"); fastcsv . write(data, { headers: true }) .

How do I download a CSV file in node JS?

log('file saved'); }); }); var file = '../software-project-metric-dashboard/file. csv'; res. download(file, 'testfile. csv');


1 Answers

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', ... ] }) 
like image 61
trognanders Avatar answered Sep 22 '22 19:09

trognanders