admin管理员组

文章数量:1397142

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 ma at the end 2. The inability to form an array and push the object into it

Any leads would be appreciated

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 ma at the end 2. The inability to form an array and push the object into it

Any leads would be appreciated

Share Improve this question asked Apr 28, 2020 at 6:27 stackUser67stackUser67 1284 silver badges13 bronze badges 2
  • for the trailing ma, wouldn't be simpler to add the + "," at the beginning and perform a check the "first append" to not include it.. – Tarounen Commented Apr 28, 2020 at 6:36
  • Probably you should try, without + sign and ma. When the next object pushed, it must be separated with ma automatically, I guess. – jkalandarov Commented Apr 28, 2020 at 6:39
Add a ment  | 

1 Answer 1

Reset to default 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"
  }
]

本文标签: javascriptHow to push object inside an array while writing to a file in Node JsStack Overflow