简体   繁体   中英

Read file component (fs.readFile)

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;

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>

}

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);
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM