javascript 写入文本或 JSON 文件以与节点反应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53449406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write to a text or JSON file in react with node
提问by Seamus
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.
我真的知道要做出反应并创建了一个基本网站作为练习,我可以从 JSON 文件呈现数据,我可以读取输入到文本框中的数据以显示在日志文件中,但我不确定如何写入文件。
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
这是我的 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
当我按下提交时,我收到一条错误消息,指出 TypeError: fs.writeFile is not a function
采纳答案by Kunal Mukherjee
To write into the file use the fsmodule in Node JS:
要写入文件,请使用fsNode JS 中的模块:
To run install:
运行安装:
npm install --save cors
npm install --save express
npm install --save body-parser
npm install --save-dev morgan
Here is the index.js file:
这是 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}!`));
回答by AlbertS
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();
}
回答by vibhor1997a
You can't write a file in a browser environment to the user's machine in any major browser. fs.writeFileis supposed to be run in a Node.jsenvironment.
您无法在任何主流浏览器中将浏览器环境中的文件写入用户机器。fs.writeFile应该在一个Node.js环境中运行。


