Is there any convenient way for nodejs to append a new array to an array in an existing json file?

here"s the thing. Now there"s a json file with an array of data, such as
users.json:

.
[
    {name: aa,age: 1}
    {name: bb,age: 2}
    {name: cc,age: 3}
    ...
]

now I want to insert a few pieces of data into the array in this json file. Note that it is not appended to json, but to the array in json. Is there any easy way to implement it? Or do you have to read out and append the array before rewriting it?

Nov.29,2021

is not necessary, but it is more convenient.
of course, you can also open it in append mode, start with the penultimate digit, and then replace the original [{}, {}] with {}, {}]

when you write.
fs.open (path, flags [, mode], callback)
fs.writeSync (fd, string [, position [, encoding]])

fs


let fs = require('fs');
 

fs.readFile('test.json','utf8',function (err, data) {
        if(err) console.log(err);
        var test1=JSON.parse(data);
        test1.data.push({"user":"li"})
        var t = JSON.stringify(test1);
        fs.writeFileSync('test.json',t)
});

//   fs push

what do you mean by convenience?
if you want to be safe, it's best to read it out and then rewrite it.
because the original in the array is ordered, and there is no comma after the last element in the file.

Menu