Reputation: 33
I've tried the below:
const fs = require('fs');
var file = fs.readFileSync("../word.txt", {encoding: 'utf8'}).toString()
but get the error Module not found: Error: Can't resolve 'fs'
. All I want is to be able to store all the .txt contents into a variable that I can manipulate. What other easy ways are there as I don't think there's any easy way to bypass this error.
Thanks a lot and please help!!
Upvotes: 1
Views: 984
Reputation: 164729
There are several ways to load the contents of a text file that is either bundled with your React project or hosted separately.
Both approaches involve loading a URL. You could make a generic function to do so...
const loadTextFile = async (url) => {
const res = await fetch(url);
if (!res.ok) {
throw res;
}
return res.text();
};
and then load the content into a state value, eg
const [word, setWord] = useState("");
useEffect(() => {
loadTextFile(process.env.PUBLIC_URL + "/word.txt")
.then(setWord)
.catch(console.error);
}, []);
import fileUrl from "./path/to/word.txt";
// ...
useEffect(() => {
loadTextFile(fileUrl)
.then(setWord)
.catch(console.error);
}, []);
useEffect(() => {
loadTextFile("https://example.com/word.txt")
.then(setWord)
.catch(console.error);
}, []);
Customise your Webpack config to add a resource query to load modules using source assets
module: {
rules: [
// ...
{
resourceQuery: /raw/,
type: 'asset/source',
}
]
},
and import your text file contents using
import word from "./path/to/word.txt?raw";
If you're using create-react-app
, this will require ejecting your configuration.
If you don't mind encoding your text file content into a JSON string literal, you can always use a .json
file.
For example, assets/word.json
"this is some plain text in a JSON file"
import jsonFileContents from "./assets/word.json";
Upvotes: 1