Search code examples
node.jsnodes

How to post data to .json file using postman in node js


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


Solution

  • 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))
     });