How can I convert from .csv to array/json/string in node.js

Viewed 14854

I have a csv file I want to use in node.js/express. How can I convert the file to a variable of type array/json/string. I've tried:

fs.readFile('Resource.csv', function(err, data) {
    console.log(data)}

And also tried a number of other things I could find in SO but none work for me. The data is of multiple rows if it matters.

2 Answers
var fs = require('fs');

var data = fs.readFileSync('Resource.csv')
    .toString() // convert Buffer to string
    .split('\n') // split string to lines
    .map(e => e.trim()) // remove white spaces for each line
    .map(e => e.split(',').map(e => e.trim())); // split each line to array

console.log(data);
console.log(JSON.stringify(data, '', 2)); // as json

To expand on my comment (from the csvtojson doc)

Install with npm i --save csvtojson

Then you use the module like this :

CSV File :

a,b,c
1,2,3
4,5,6

JS Code :

const csvFilePath='<path to csv file>' // Resource.csv in your case
const csv=require('csvtojson') // Make sure you have this line in order to call functions from this modules
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
})

Output :

[
  {a:"1", b:"2", c:"3"},
  {a:"4", b:"5". c:"6"}
]
Related