1

How to push object inside an array while writing to a file in Node Js? I currently have the following working code

fs.appendFile("sample.json", JSON.stringify(data, undefined, 2) + ",");

where data is an object, like

{
name:'abc',
age: 22,
city: 'LA'
}

Upon appending, which results the following

{
name:'abc',
age: 22,
city: 'LA'
},
{
name:'def',
age: 25,
city: 'MI'
},

I see 2 problems here. 1. The trailing comma at the end 2. The inability to form an array and push the object into it

Any leads would be appreciated

2
  • for the trailing comma, wouldn't be simpler to add the + "," at the beginning and perform a check the "first append" to not include it.. Commented Apr 28, 2020 at 6:36
  • Probably you should try, without + sign and comma. When the next object pushed, it must be separated with comma automatically, I guess. Commented Apr 28, 2020 at 6:39

1 Answer 1

7

Append will append your data to a file and here data is being treated as a string and all appends will be equal to concating string to another string.

Instead, here the file needs to be read first and converted to a data-structure for this example it can be an array of objects and convert that data-structure to string and write it to file.

To write to the file

fs.writeFileSync('sample.json', JSON.stringify([data], null, 2));

sample.json

[
  {
    "name": "abc",
    "age": 22,
    "city": "LA"
  }
]

Read from file

const fileData = JSON.parse(fs.readFileSync('sample.json'))
fileData.push(newData)

Write the new data appended to previous into file

fs.writeFileSync('sample.json', JSON.stringify(fileData, null, 2));

sample.json

[
  {
    "name": "abc",
    "age": 22,
    "city": "LA"
  },
  {
    "name": "abc",
    "age": 22,
    "city": "LA"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.