1

Can anyone change below node is code as per expected output as I mentioned below. I post it using client API

My output:

 [
        {
            "name": "alpha",
            "password": "beta",
            "id": 5
        }
    ]
 {
            "name": "abc",
            "password": "123",
            "id": 6
        }

Expected output should be :

[
    {
        "name": "alpha",
        "password": "beta",
        "id": 5
    },
    {
        "name": "abc",
        "password": "123",
        "id": 6
    }
]

My code :

var fs = require('fs');
var express = require('express');
var app = express();

app.post('/myData', function (req, res) {
    req.on('data', function (data) {
        console.log(data.toString());
        fs.appendFile("test.json", data, 'utf8', function (err, file) {
            if (err) { return console.log(err); }
            console.log("The file was saved!");
            res.send("Received");

        });
    });
});

var server = app.listen(8080, function () { });

Please anyone help me to achieve this method by editting the above code I use chorme extension Advanced REST client for posting the data to test.json

Dark Ninja
  • 149
  • 2
  • 13

1 Answers1

1

first read the file , then parse the json data , and push object to an array and write file

 var fs = require('fs')  
  var obj = {};

  fs.readFile('output.json', function (err, data) {
        var json = JSON.parse(data)
        json.push(obj);

        fs.writeFile("output.json", JSON.stringify(json))
 });
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
  • now my output is like this data is not writing empty bracket only coming { } after the pre existing data [ { "name": "alpha", "password": "beta", "id": 5 }, { } ] – Dark Ninja Oct 17 '18 at 17:16