Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.