与节点反应写入文本或JSON文件

与节点反应写入文本或JSON文件

本文介绍了与节点反应写入文本或JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很会做出反应,并按照惯例创建了一个基本网站,我可以从JSON文件中渲染数据,并且可以读取输入到文本框中的数据以显示在日志文件中,但是我不确定如何处理写入文件.

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

这是我的App.js

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;

当我按下Submit时,我收到一条错误消息,提示TypeError:fs.​​writeFile不是函数

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

推荐答案

要写入文件,请使用 JS节点中的"> fs 模块:

要运行安装:

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}!`));

这篇关于与节点反应写入文本或JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:37