2

While using https://www.npmjs.com/package/convert-csv-to-json in reactjs.I am getting error Uncaught TypeError: fs.readFileSync is not a function

import React, { Component } from 'react'
import { connect } from 'react-redux'
import $ from 'jquery';
export default class CsvRead extends React.Component {
  constructor(props) {
    super(props);
  }
  CsvRead() {
    let csvToJson = require('convert-csv-to-json');
    let json = csvToJson.getJsonFromCsv("../../MonthlySummaryDetailsCSV.csv");
    for(let i=0; i<json.length;i++){
    console.log(json[i]);
    }

  }
  render() {
    return (
      <div >{this.CsvRead()}</div>
    );
  }
}

Anyone can help me on this?

Manish J
  • 686
  • 1
  • 8
  • 24

2 Answers2

5

convert-csv-to-json is meant to work with fs which stands for filesystem. That means it will only work in Node environments, not browser environments.

If you need to convert CSV to JSON/JS in the browser, you could see this question for a way to do that.

Andy_D
  • 4,112
  • 27
  • 19
0
    import * as XLSX from 'xlsx'

const SheetJSFT = [
    "xlsx",
    "xlsb",
    "xlsm",
    "xls",
    "xml",
    "csv",
    "txt",
    "ods",
    "fods",
    "uos",
    "sylk",
    "dif",
    "dbf",
    "prn",
    "qpw",
    "123",
    "wb*",
    "wq*",
    "html",
    "htm"
].map(x=>`.${x}`).join(",");

export const useCsvUpload = () => {
    const handleFileReader = (file, callback) => {
        /* Boilerplate to set up FileReader */
        const reader = new FileReader();
        const rABS = !!reader.readAsBinaryString;
        reader.onload = (e) => {
            /* Parse data */
            const bstr = e.target.result;
            const wb = XLSX.read(bstr, { type: rABS ? 'binary' : 'array', bookVBA: true });
            /* Get first worksheet */
            const workSheetName = wb.SheetNames[0];
            const workSheet = wb.Sheets[workSheetName];
            /* Convert array of arrays */
            const jsonData = XLSX.utils.sheet_to_json(workSheet).map(item => ({
                ...item,
                key: item.__rowNum__,
            }))
            /* Update state */
            callback(jsonData)
        };

        if (rABS) {
            reader.readAsBinaryString(file);
        } else {
            reader.readAsArrayBuffer(file);
        };
    }

    return {
        handleFileReader,
        sheetAccepted: SheetJSFT
    }
}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 27 '22 at 22:58