Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to a text or JSON file in react with node

I am really knew to react and have created a basic website as practice, i can render data from a JSON file and i can read data entered into a text box to show in the log file but i am not sure how i can write to a file.

Hoping someone can point me in the right direction to show how i can write to a file in my applications

This is my App.js

import React, { Component } from 'react';
//import PostList from './posts/YourDetails'
import { BrowserRouter, Switch} from 'react-router-dom';
import { Route} from 'react-router-dom';
import ReactDom from 'react-dom';

import './App.css';
import './index.css';
import './home.css';

import YourCar from "./Components/YourCar";
import BuyPolicy from "./Components/BuyPolicy";
import Invoice from "./Components/Invoice";
import DriveCarefully from "./Components/DriveCarefully";
import Error from "./Components/Error";
import Navigation from "./Components/Navigation";
import Footer from "./Components/Footer";
import pDetails_Name from "./Components/PersonalDetails/pDetails_Name";
import pDetails_Dob from "./Components/PersonalDetails/pDetails_Dob";
import pDetails_Add from "./Components/PersonalDetails/pDetails_Add";
import firstStage from "./Components/CompletePage/firstStage";
import YourCar_drivingDetails from "./Components/YourCar/YourCar_drivingDetails";
import home from "./Components/home";




class App extends Component {
  render() {
    return (
         <BrowserRouter>
            <div>
              <Navigation / >
                 <Switch>
                     <Route path="/" component={pDetails_Name} exact/ >
                     <Route path="/YourCar" component={YourCar}/ >
                     <Route path="/BuyPolicy" component={BuyPolicy}/ >
                     <Route path="/Invoice" component={Invoice}/ >
                     <Route path="/DriveCarefully" component={DriveCarefully}/ >
                      <Route path="/pDetails_Name" component={pDetails_Name}/ >
                      <Route path="/pDetails_Dob" component={pDetails_Dob}/ >
                      <Route path="/pDetails_Add" component={pDetails_Add}/ >
                      <Route path="/firstStage" component={firstStage}/ >
                      <Route path="/YourCar_drivingDetails" component={YourCar_drivingDetails}/ >
                     <Route component={Error}/ >
                 </Switch>
               <Footer / >
            </div>
        </BrowserRouter>
    )
  }

}

export default App;

This is an example details page with a basic function called add word, i am trying to be as simple as possible and just write a sentence to a text file when the submit button is pressed.

import {NavLink} from 'react-router-dom'
import React, {Component } from 'react'
var fs = require('fs');




function addWord(req, res) {
     var path = "test.txt";

            var str = "test string"
            var buf = Buffer.from('written from a buffer', 'utf8')

           fs.writeFile(path, str);
       }


class pDetails_Name extends Component{
        /*const pDetails_Name = () => {*/

 constructor(props){
           super(props)
           this.state = {
                           FirstName: ""

             }
 }



handleSubmit =(event)=> {
     event.preventDefault()
     const data = this.state;
     console.log("The name entered is: " , data);

               addWord();


}

handleInputChange =(event)=>{

    event.preventDefault()



    this.setState({
       [event.target.name]:event.target.value
    })
}

render(){
            const {FirstName} = this.state;

        return(
        <div id="Overhead">
            <div className="borderText">
                          Lets get some details
            </div>

         <div className ="container">

                               <form onSubmit ={this.handleSubmit} action="/action_page.php">

                                  <div className="row">
                                       <div className="col-25">
                                          <label>First Name:</label>
                                       </div>
                                       <div className="col-75">

                                       <p>Firstname is: {FirstName}</p>
                                              <input type="text" id="firstName" name="FirstName" placeholder="Your first name.. " onChange={this.handleInputChange}/>
                                              <p><button> Send Message</button></p>


                                       </div>
                                  </div>

                                  <div className="row">
                                        <div className="col-25">
                                            <label>Surname:</label>
                                        </div>
                                        <div className="col-75">
                                              <input type="text" id="lastName" name="Surname" placeholder="Your surname.."/>
                                        </div>
                                  </div>


                                   <div className="row">
                                        <div className="col-25">
                                            <label>Title</label>
                                        </div>
                                        <div className="col-75">
                                             <select>
                                                <option value="Mr">Mr</option>
                                                <option value="Miss">Miss</option>
                                                <option value="Mrs">Mrs</option>
                                                <option value="Dr">Dr</option>
                                             </select>
                                        </div>
                                  </div>


                                  <div className="row">
                                        <div className="col-25">
                                            <label>Email:</label>
                                        </div>
                                        <div className="col-75">
                                              <input type="text" id="email" name="Email" placeholder="Your email.."/>
                                        </div>
                                  </div>

                              <div >

                             <div className="borderButtons">
                                <ul className="header">

                                  <li className ="borderLinks" type="label"><NavLink id="nav" to="/">Back</NavLink></li>
                                  <li className ="borderLinks" type="label"><NavLink id="nav" to="/pDetails_DOB">Next</NavLink></li>

                                </ul>
                              </div>
                            </div>

                               </form>
                   </div>
            </div>

        )
      } //end of render


}


export default pDetails_Name;

When i press submit i get an error saying that TypeError: fs.writeFile is not a function

enter image description here

like image 596
Seamus Avatar asked Nov 23 '18 15:11

Seamus


People also ask

How do you add data to JSON file in React JS?

To load JSON from file, you have to have the raw . json file saved in your /src directory. In Create React App, you can directly import the JSON file and it will work as if it were a JS object, no need to parse it again. To load JSON from file, import it into your component.

How do you write data into file in React JS?

If you want to write to a file, you would need to send an API request from your browser / React to a server and have that server write to the file system. Additionally, as pointed out by Huy Nguyen, it's possible to write to the clients file system from the browser but that is going to be private to that user.

How do you read and write to local JSON files from React JS?

To Fix read and write to local JSON files from React. js, Importing and reading from json can be like: import data from './data/data. json'; then use . map() to iterate data.


1 Answers

Client side solution:

const handleSaveToPC = jsonData => {
  const fileData = JSON.stringify(jsonData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = 'filename.json';
  link.href = url;
  link.click();
}
like image 166
AlbertS Avatar answered Oct 08 '22 19:10

AlbertS