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
1 Answer
Reset to default 7Append 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
版权声明:本文标题:javascript - How to push object inside an array while writing to a file in Node Js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744113496a2591402.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论