最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to push object inside an array while writing to a file in Node Js - Stack Overflow

programmeradmin4浏览0评论

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"
  }
]
发布评论

评论列表(0)

  1. 暂无评论