0

I am facing an issue while using csvtojson package. I am trying to convert CSV to json. I am using https://www.npmjs.com/package/csvtojson package and I tried https://www.npmjs.com/package/convert-csv-to-json this package also in both I am getting **Cannot find module 'fs' ** this error.

import csv from 'csvtojson';
  csv()
    .fromFile(csvFilePath)
    .then((jsonObj) => {
        console.log(jsonObj);
    })

"react": "^16.13.0", "csvtojson": "^2.0.10", "webpack": "^4.46.0", "webpack-cli": "^3.3.12"

Manju Prem
  • 39
  • 6
  • Does this answer your question? [Node JS fs module inside browser](https://stackoverflow.com/questions/27019242/node-js-fs-module-inside-browser) – Noah Mar 28 '21 at 19:12

1 Answers1

0

csvtojson module is a comprehensive nodejs csv parser to convert csv to json or column arrays.

You can not use all nodejs libs on the frontend side.

You can parse lines, but take care of validations and special characters.

const rowSeparator = "\n";
const columnSeparator = ",";
function csvJSON(csv){
  let lines=csv.split(rowSeparator);
  let result = [];
  var headers=lines[0].split(columnSeparator);
  lines.splice(0, 1);
  for(let line of lines){
      let columns = line.split(columnSeparator);
      let row = {};    
      for(let header of headers){
          row[header] = columns[headers.indexOf(header)];
      }
      result.push(row);

  }
  return JSON.stringify(result);
}

Example:

csvJSON("aa,bb\n1,2\n2,5")
"[{"aa":"1","bb":"2"},{"aa":"2","bb":"5"}]"
Akif Hadziabdic
  • 2,241
  • 1
  • 8
  • 20
  • How can I fix this issue? – Manju Prem Mar 28 '21 at 18:35
  • It seems to be the "file retrieval" part that's breaking, not the "CSV parsing" part. If so, then I don't think this answer helps. As far as this answer goes, though, there are proven, pre-packaged functions they should use instead. For instance, as of this writing, this answer does not account for quoted or escaped commas. – Noah Mar 28 '21 at 19:09