简体   繁体   中英

How to save different objects in one array in json using node js

I have a form where there are two inputs.I want to save every form details in JSON in one array.... This is my HTML code.....

  <form action="/saveData" method="post">
        First Name: <input type = "text" name = "fname"> <br>
        Last Name: <input type = "text" name = "lname">
        <input type = "submit" value = "Submit">
  </form>

I am saving this data in JSON file users.json using node js...

My node js code is this...

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
const { json } = require('body-parser');
const fs = require('fs');
const PORT = 5000;
var http = require('http');
const path = require('path')

// http.createServer(function (req, res) {
//   res.writeHead(200, {'Content-Type': 'text/html'});
//   res.end('Hello World!');
// }).listen(8080);336

app.use(express.static('files'))

app.use(express.static(path.join(__dirname, 'public')));

//========================reading file from json============================//

let urlencoded = bodyParser.urlencoded({ extended: true })
app.post('/saveData', urlencoded,function(req, res) {

  var myData = {
    "name": req.body.fname,
    "lastname": req.body.lname
  }

 var  formData = JSON.stringify(myData);
  console.log(formData);

  //=========================############// writing data to json //############========================//

  fs.writeFile('./user.json',formData, function (err) {
    if (err) {
      console.log(err);
    }
  })

  res.send("DATA SAVED SUCCESSFULLY");
});

app.listen(PORT, () => {
  console.log(`Listening on ${PORT}`)
})

The result appears in JSON file is something like this....

{"name":"Azhar","lastname":"khan"}

Every time I submit a form,instead of adding the data in JSON file it replace the old data with the new one and every time it only replace it...... I want to add the new form data with the old ones as different objects in one array.....How can I do that.Thank in Advance

app.post('/saveData', urlencoded, function (req, res) {
    var list = [];
    var FILE_NAME = './user_list.json';

    if (fs.existsSync(FILE_NAME)) {
        var string = fs.readFileSync(FILE_NAME)
        try{ list = JSON.parse(string) } catch(e) { }
    }

    list.push({
        "name": req.body.fname,
        "lastname": req.body.lname
    })

    fs.writeFile(FILE_NAME, JSON.stringify(list), function (err) {
        if (err) {
            console.log(err);
            res.send({ status: false, message: err })
            return
        }
        res.send("DATA SAVED SUCCESSFULLY");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM