2

Im getting an error stating that fs.readFile is not a function. What am I not understanding about how to use fs.readFile?

https://www.geeksforgeeks.org/node-js-fs-readfile-method/

The objective here is to get the contents of my file into a variable and parse thought the value further.

import React from 'react';


const fs = require('fs')

const ToolTipTextMod = (props) => {
    let txt = null;
    fs.readFile('../../components/ToolTip/ToolTipText.txt',(err, data) => {console.log(data)})

    return(
        <p>{txt},{props.textId}</p>

    );
}

export default ToolTipTextMod;
  • You cannot mix functions from `node.js` API that are meant to be run from a command line localy with client Javascript which is ment to run in a browser window, where there are no files. There is no way to use `readFile` in the browser. – px1mp Jun 17 '20 at 21:52
  • 1
    Don't use `fs` in React: it's an API for working with the filesystem, something that page JS very much will never be able to do. Presumably you're bundling your React code with webpack (like everyone else), in which case you load data using a webpack loader, such as the [raw-loader](https://webpack.js.org/loaders/raw-loader/) for loading files as string data, with your JS code using `import`/`require` for the files you need in the exact same way you `import`/`require` JS code. Webpack will then make sure things work. – Mike 'Pomax' Kamermans Jun 17 '20 at 21:53
  • You can use `fetch` to load text files. Refer here https://stackoverflow.com/a/50570949/311255 – SelvaS Jun 17 '20 at 23:23

2 Answers2

5

fs is a Nodejs module. So I would recommend using a package like raw-loader , but for that you need to have webpack setup.

So alternate way is to simply use fetch/Axios.

Example:

 import React, {useState,useEffect} from "react";
 import txt from "./test.txt"; // Your file path 
 import Axios from "axios"; // Import Axios or use Fetch.


const ToolTipTextMod = (props) => {
const [text,setText] = useState("");

useEffect(()=>{
   Axios(txt).then(res => setText(res.data)); // This will have your text inside data attribute
},[])

return <p>/* code */</p>

}
Thanveer Shah
  • 3,250
  • 2
  • 15
  • 31
  • This has defiantly going in the right direction. I was able to log the expected text. However im having a bit of difficulty deconstructing the axios call. How can I get the res.data value into a variable? – Christian Cuneo Jun 17 '20 at 23:03
  • @ChristianCuneo Just create a state and put it inside it, I have updated the answer :) – Thanveer Shah Jun 17 '20 at 23:05
-1

fs.readFile() is for NodeJs, for frontend react you can use FileReader():

  const handleReadFile = () => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const fileContents = e.target.result;
      console.log(fileContents);
      setText(fileContents);
    };
    reader.readAsText(selectedFile);
  };
kenjigoh
  • 39
  • 4