Levin Kent
Levin Kent

Reputation: 33

Struggling to store .txt file in a variable as string

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

Answers (1)

Phil
Phil

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.

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

Upvotes: 1

Related Questions