I'm trying to get some data from a simple form and write a JSON file using node JS and FS.
I need this:
[{"id":1,"answer1":"C","answer2":"C"},{"id":2,"answer1":"A","answer2":"A"}]
This is the code I wrote:
const express = require("express");
const fs = require('fs');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/form.html")
});
app.post("/", function(req, res) {
let result1 = req.body.question1;
let result2 = req.body.question2;
const dataFile = require("./data.json");
const userAnswers = {
id: dataFile.length + 1,
answer1: result1,
answer2: result2,
};
dataFile.push(userAnswers);
fs.writeFile("data.json", JSON.stringify(dataFile), 'utf8', function(err) {
if (err) {
console.log("An error occured while writing JSON Object to File.");
return console.log(err);
}
console.log("JSON file has been saved.");
});
res.sendFile(__dirname + "/form.html");
});
app.listen(3000, function() {
console.log("The server is running on 3000")
});
It actually works, the JSON file gets created and when I click on the submit button the inputs disappear, then I can continue putting new data.
The problem is that when I refresh the page, the last input gets duplicated in my JSON file. I don't know how to reset it. May someone help me?
question from:
https://stackoverflow.com/questions/65660601/how-to-not-duplicate-data-when-using-fs-writefile 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…