Home > Blockchain >  Can React Js edit/wite to a file that is stored in its src or public folder
Can React Js edit/wite to a file that is stored in its src or public folder

Time:03-10

I intend to use a text file that is located within my src / public folder as a sort of database. My question is simple; Can React Js edit a .txt file that is stored in the src/public folder of my web app ( my app bundle ) ?

I am not asking if my app can edit/access files that are stored in my clients file system.

Thanks in advance.

CodePudding user response:

No, react's code runs on the client machine, so it can just fetch files from src or public folders. You can arrange this for example via a backend API.

CodePudding user response:

React itself has no capabilities to write/edit files in your web server. You would need another library to write to files (like 'fs' or other alternatives). So you'd want React to talk to 'fs' somehow, and tell it 'when i click this button, write to a file'.

However, React generally runs in the browser, and your files are stored on the server, so you will not be able to write to a file within React scope directly. you will need React to talk to the server (via fetch most likely) and the server can talk to 'fs' and tell it to write to a file. so the overall setup would look something like this:

Client Side:

  • User types into an input in browser UI (React)
  • User clicks button in browser UI (React)
  • React onClick handler sends a request (fetch) to a server endpoint with the desired text to write to the file ('post' or 'patch' request with a body that has the text)

Server Side:

  • Server endpoint handles the request, reads the body data (desired text)
  • Server endpoint tells 'fs' 'Here's the text I want you to write to the file'
  • Server completes, responds to browser
  • Related