0

With reactjs, I tried to use fs to read a text file line by line, but then the compiler complains "Module not found: Error: Can't resolve 'fs'. I browsed the internet, it's well known reactjs bug for webpack 5, people asked to go down to webpack 4.

I have the following questions:

  1. How to go down from webpack 5 to webpack 4? Will it be affect the other codes?

  2. Is there any other way to read text file line by line without using fs?

Thanks!

user7087799
  • 73
  • 1
  • 9
  • It's not a bug, `fs` is a *node* module, used to interact with the file system on the backend. You can't use it in the browser. You'll need to find a _front end_ method for reading the file, check Jonathan's answer – Jayce444 Dec 15 '22 at 01:57

1 Answers1

0

Downgrading should be fine but have you considered using the javascript fetch() or FileReader() commands.

From the browser

const fileReader = new FileReader();
fileReader.onload = event => {
  const fileText = event.target.result;
  const lines = fileText.split('\n');
  // do something with the lines here...
};
fileReader.readAsText(file);

From the server

fetch(url)
  .then(response => response.text())
  .then(fileText => {
    const lines = fileText.split('\n');
    // do something with the lines here...
  });
Jonathan
  • 2,318
  • 7
  • 25
  • 44
  • Thanks for your help! From the browser, I copied your code, but got the following error : Uncaught TypeError TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'. – user7087799 Dec 15 '22 at 04:49
  • 1
    You need to use the Blob type object. `const file = new Blob([file], {type: 'text/plain'});` – Jonathan Dec 15 '22 at 04:58
  • By the way, I am reading a local file, import it from the directory. I have used your second method, but got the following error : Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'split') at ( – user7087799 Dec 15 '22 at 05:03
  • Use `FileReader` for browser the second method is from server – Jonathan Dec 15 '22 at 05:07
  • The syntax you provide is not right, so I used const file = new Blob(CategoriesFile).text(), but I got the following error : Uncaught TypeError TypeError: Failed to construct 'Blob': The provided value cannot be converted to a sequence. – user7087799 Dec 15 '22 at 05:09
  • My file content look like the following : GOOGLE, MISC AMZN, MERCHANDISE MCDONALD, DINNING CLICKBANK, MERCHANDISE SAFEWAY, GROCERIES – user7087799 Dec 15 '22 at 05:10
  • Even I use the following syntax : const file = new Blob(CategoriesFile, { type: "text/plain" }). I got the same error. – user7087799 Dec 15 '22 at 05:13