Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access file system (like react-native-fs module) with create-react-app project?

I'm pretty new to working with React, but I've done some tutorials and I feel comfortable using create-react-app to start a project and use npm to install other modules. Specifically, I've been following a tutorial on LinkedIn Learning to create a basic appointment scheduling app in React. In short, I decided I wanted to expand on the tutorial by writing the appointments to a json file on the server side so appointment changes would be preserved across.

My problem is, I can't get the Node.js File System Module or the React Native FS Module to work in my project. When I try using the former, I do so using this code:

import React from 'react';
import '../css/App.css';

import AddAppointments from './AddAppointments';
import SearchAppointments from './SearchAppointments';
import ListAppointments from './ListAppointments';

import {without} from 'lodash';
var fs = require('fs');

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      myAppointments: [],
      formDisplay: false,
      lastIndex: 0,
    };
    this.addAppointment = this.addAppointment.bind(this);
    this.deleteAppointment = this.deleteAppointment.bind(this);
    this.toggleForm = this.toggleForm.bind(this);
  }

  toggleForm() {
    this.setState({
      formDisplay: !this.state.formDisplay,
    });
  }

  addAppointment(apt) {
    let tempApts = this.state.myAppointments;
    apt.aptID = this.state.lastIndex;
    tempApts.unshift(apt);
    this.setState({
      myAppointments: tempApts,
      lastIndex: this.state.lastIndex + 1,
    });
    fs.writeFile('./data.json', tempApts, (err) => {
      if (err) throw err;
      console.log('Saved!');
    });
  }

  deleteAppointment(apt) {
    let tempApts = this.state.myAppointments;
    tempApts = without(tempApts, apt);

    this.setState({
      myAppointments: tempApts,
    })
  }

  componentDidMount() {
    fetch('./data.json')
      .then(response => response.json())
      .then(result => {
        const apts = result.map(item => {
          item.aptID = this.state.lastIndex;
          this.setState({lastIndex: this.state.lastIndex+1});
          return item;
        });
        this.setState ({
          myAppointments: apts,
        });
      });
  }

  render() {
    return (
      <main className="page bg-white" id="petratings">
        <div className="container">
          <div className="row">
            <div className="col-md-12 bg-white">
              <div className="container">
                <AddAppointments
                  formDisplay={this.state.formDisplay}
                  toggleForm={this.toggleForm}
                  addAppointment={this.addAppointment}
                />
                <SearchAppointments />
                <ListAppointments
                  appointments={this.state.myAppointments}
                  deleteAppointment={this.deleteAppointment}
                />
              </div>
            </div>
          </div>
        </div>
      </main>
    );
  }
}

export default App;

The relevant bit is that I include "var fs = require('fs');" at the top of my code and try to access the file system (writing a file) with "fs.writeFile()". When I try this, the code throws an error when I click the button that runs addAppointment():

    37 |   myAppointments: tempApts,
    38 |   lastIndex: this.state.lastIndex + 1,
    39 | });
  > 40 | fs.writeFile('./data.json', tempApts, (err) => {
       | ^  41 |   if (err) throw err;
    42 |   console.log('Saved!');
    43 | });

After looking into this, I saw that the Node.js file system cannot be used with React. So I tried the other module, by following its instructions to install and link it, making sure that it's in the package.json and assigning it in the code with "var RNFS = require('react-native-fs');" and using it later as "RNFS.writeFile()". The problem here is, I'm immediately thrown the following error as my program fails to compile:

./node_modules/react-native-fs/FS.common.js
SyntaxError: D:\react-ui\reactinterface\node_modules\react-native-fs\FS.common.js: Unexpected token, expected "," (30:29)

  28 | };
  29 | 
> 30 | var normalizeFilePath = (path: string) => (path.startsWith('file://') ? path.slice(7) : path);
     |                              ^
  31 | 
  32 | type MkdirOptions = {
  33 |   NSURLIsExcludedFromBackupKey?: boolean; // iOS only

Can anyone tell me what I'm missing? I'd really like to have server-side file system access in future programs.

like image 302
digitalspaces Avatar asked Jun 17 '26 13:06

digitalspaces


1 Answers

React app is compiled to work on the browser, u can't use node FileSystem in a browser app, and the React Native FS Module is a React native package (android, ios)

like image 132
elkhayder Avatar answered Jun 19 '26 02:06

elkhayder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!