写入文本或 JSON 文件以与节点react

IT技术 javascript node.js reactjs
2021-05-01 12:20:06

我真的知道要做出react并创建了一个基本网站作为练习,我可以从 JSON 文件呈现数据,我可以读取输入到文本框中的数据以显示在日志文件中,但我不确定如何写入文件。

希望有人能指出我正确的方向,以展示我如何在我的应用程序中写入文件

这是我的 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;

这是一个示例详细信息页面,具有称为添加单词的基本功能,我试图尽可能简单,并在按下提交按钮时将句子写入文本文件。

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;

当我按下提交时,我收到一条错误消息,指出 TypeError: fs.writeFile is not a function

在此处输入图片说明

3个回答

客户端解决方案:

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();
}

要写入文件,请使用fsNode JS 中module:

运行安装:

npm install --save cors
npm install --save express
npm install --save body-parser
npm install --save-dev morgan

这是 index.js 文件:


// index.js
const cors = require('cors');
const express = require('express');
const morgan = require('morgan');
const fs = require('fs');
const bodyParser = require('body-parser');
const promisify = require('util').promisify;

const app = express();
const port = 5000;
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cors());
app.options('*', cors());

const writeFilePromise = promisify(fs.writeFile);

WriteTextToFileAsync = async (contentToWrite) => {

    try {
        // FIXME: give your own path, this is just a dummy path
        const path = 'C:\\foo.txt';
        await writeFilePromise(contentToWrite, path);
    } catch(err) {
        throw new Error(`Could not write file because of {err}`);
    }
}



// Default route
app.get('/', (req, res) => res.status(200).send({ message : 'Hello world' }));


// Write route
app.use('/write', async (req, res, next) => {

    try {
        //FIXME: Simply write the entire request body for now
        const fileContent = req.body;
        await WriteTextToFileAsync(fileContent);
        return res.status(200).send( { message: 'File written successfully!' });
    } catch (err) {
        throw new Error(`Could not write file because of {err}`);
    }
});

// Not-found route
app.use((req, res, next) => {
    res.status(404).send({ message: 'Could not find the specified route you requested!' });
});

app.listen(port, () => console.log(`Server up and running and listening for incoming requests on port ${port}!`));

您无法在任何主流浏览器中将浏览器环境中的文件写入用户机器。fs.writeFile应该在一个Node.js环境中运行