6

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.

5
  • npmjs.com/package/csvtojson Commented Oct 28, 2018 at 12:31
  • I've tried that and get: TypeError: csv(...).fromFile(...).then is not a function Commented Oct 28, 2018 at 12:40
  • Are you sure you installed and required the npm module ? Commented Oct 28, 2018 at 12:49
  • Yes. @L.Faros I am sure. Commented Oct 28, 2018 at 13:01
  • Also, if you require the module with const csvtojson=require('csvtojson') then you should use csvtojson(...).fromFile(...).then Commented Oct 28, 2018 at 13:01

2 Answers 2

19
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
Sign up to request clarification or add additional context in comments.

5 Comments

I get weird characters in console. Possibly encoding is wrong.
Use fs.readFileSync('Resource.csv', <codepage>). Often console doesn't work with utf-8 (and national localizes) correctly.
This solution does not works if any field of the csv contains a ',' character.
Great solution - very neat
Nope. This solution works only with simplest csv that suitable in most cases. According to Wiki csv values can be quoted and contain \n. You should use a special library for production.
6

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"}
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.