Grant Campbell
Grant Campbell

Reputation: 143

Node.JS append JSON to array

I need to append my JSON data to an array inside a JSON file. It is appending successfully. However, it does not append inside of the Brackets in the JSON file

Here is my NODE

 if (req.method == 'POST') {
    req.on('data', function (chunk) {
        fs.writeFile("comments-data.json", chunk, {'flag':'a'}, function(err) {
            if(err) {
                return console.log(err);
            }

            console.log("The file was saved!");
        })
    });
    res.end('{"msg": "success"}');
};

How can i tell it to just append inside of the brackets?

Upvotes: 1

Views: 5436

Answers (1)

Barmar
Barmar

Reputation: 780889

You have to parse the JSON in both the request and the file, push the requrest data onto the array, then write that back out to the file.

if (req.method == 'POST') {
    req.on('data', function(chunk) {
        var element = JSON.parse(chunk);
        fs.readFile("comments-data.json", 'r', function(err, json) {
            var array = JSON.parse(json);
            array.push(element);
            fs.writeFile("comments-data.json", JSON.stringify(array), "w", function(err) {
                if (err) {
                    console.log(err);
                    return;
                }
                console.log("The file was saved!");
            });
        });
        res.end('{"msg": "success"}');
    });
}

Upvotes: 2

Related Questions