Dusky Dood
Dusky Dood

Reputation: 307

How to Post data from postman to Output.json file?

In the below code I am getting output like this without comma it's creating new array again I don't want like this I want like lastly I mentioned

Test.json

[
    {
        "name":"alpha",
        "password": "123"
    },
    {
        "name":"beta",
        "password": "321"
    }
]{
  "name":"Gokul",
  "pass":"098"
}

Main.js

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 () { });

But i want output like this :

[
    {
        "name":"alpha",
        "password": "123"
    },
    {
        "name":"beta",
        "password": "321"
    },
    {
        "name":"gokul",
        "password": "098"
    }
]

Can anyone help me and edit my code to the expected output?

Upvotes: 2

Views: 1284

Answers (2)

Gafar Popoola
Gafar Popoola

Reputation: 21

STOP!! Don't reinvent the wheel, what you need is similar to a local JSON database like Lowdb. Why don't you take a look at this repository. Perfect for your use case.

Upvotes: 0

blue112
blue112

Reputation: 56472

What you want is to merge the jsons together.

What you need to do is, in that order:

  1. Read the full test.json file
  2. Parse the content as json
  3. Push the json the received into the array
  4. Write it back as a json file (stringify it before)

Upvotes: 2

Related Questions