1

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!!

Levin Kent
  • 33
  • 4
  • 2
    You can't access local files from a website. Imagine that you could read someone's entire file system if it would be possible. – Konrad Aug 15 '22 at 07:08

1 Answers1

1

There are several ways to load the contents of a text file that is either bundled with your React project or hosted separately.

  1. Put the file in the public folder and fetch it via direct URL.
  2. Import the file which will use Webpack's general asset module to bundle and emit a URL you can load.
  3. Host the file somewhere on the public internet on a server configured with CORS access. AWS S3 for example

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("");

Option #1 - public folder

useEffect(() => {
  loadTextFile(process.env.PUBLIC_URL + "/word.txt")
    .then(setWord)
    .catch(console.error);
}, []);

Option #2 - asset

import fileUrl from "./path/to/word.txt";

// ...

useEffect(() => {
  loadTextFile(fileUrl)
    .then(setWord)
    .catch(console.error);
}, []);

Option #3 - online

useEffect(() => {
  loadTextFile("https://example.com/word.txt")
    .then(setWord)
    .catch(console.error);
}, []);

Edit peaceful-chaum-8k7l60


Bonus round - custom webpack config

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.


The JSON option

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";
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Thanks so much mate, I have a lot to learn and I appreciate the detailed response. One other I approach I had was to store the .txt as a multiline string in a .js file and to then export it but that approach didn't feel good to me, yours is great! – Levin Kent Aug 15 '22 at 08:11
  • 1
    @LevinKent oh, you can put the contents into a `.json` file and import that directly. I'll update my answer – Phil Aug 15 '22 at 08:14
  • Hey again @Phil, just wondering, is it possible in react to extract a .txt file from a Url i.e (https://github.com/itsfoss/text-files/blob/master/sherlock.txt) and store as a variable that can be passed in to the functions you've created above? Thanks again – Levin Kent Aug 18 '22 at 04:50
  • 1
    @LevinKent absolutely. You just fetch the URL like you would any other online resource, using the exact same `loadTextFile` function as above. The server hosting the file would need to have CORS access configured though. – Phil Aug 18 '22 at 04:57
  • 1
    @LevinKent I've added an example to my answer... option #3 – Phil Aug 18 '22 at 05:04
  • Thanks a bunch and yeah that makes sense, unfortunately, most .txt files don't work on my site due to the CORS access restriction. I'm going to try follow this https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors to try bypass. Do you approve boss? – Levin Kent Aug 18 '22 at 05:35
  • 1
    The answers on that question are good. Really the only option is to use a proxy – Phil Aug 18 '22 at 05:40