Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  182] [ 4]  / answers: 1 / hits: 8959  / 4 Years ago, wed, june 17, 2020, 12:00:00

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;

More From » reactjs

 Answers
1

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>

}

[#3449] Tuesday, June 16, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Tue, May 26, 20, 00:00, 4 Years ago
;