Stack Overflow Asked by thomas bouasli on January 3, 2022
I have an JSON file that holds an array of objects, like so:
[
{ "id": 1, "name": "JavaScript Begginer", "duration": "10 Hours" },
{ "id": 2, "name": "JavaScript Intermediate", "duration": "15 Hours" },
{ "id": 3, "name": "JavaScript Advanced", "duration": "20 Hours" }
]
and I wish to add a new object to it using Node, can this be accomplished with the File System Module?
Here is where I want the change to be made:
app.post("/api/courses", (req, res) => {
const course = {
id: courses.length + 1,
name: req.body.name,
};
res.send(course);
courses.json.push(course); //Something like this
});
I did try fs.appendFile but it returns this:
[
{ "id": 1, "name": "JavaScript Begginer", "duration": "10 Hours" },
{ "id": 2, "name": "JavaScript Intermediate", "duration": "15 Hours" },
{ "id": 3, "name": "JavaScript Advanced", "duration": "20 Hours" }
]
[object Object]
Check out lowdb... its a fs based wrapper for working with json file as your persisted storage method:
Answered by jremi on January 3, 2022
1 Asked on February 6, 2021 by thisara-watawana
1 Asked on February 6, 2021 by berco-beute
5 Asked on February 6, 2021 by domeniko
1 Asked on February 6, 2021 by sampleuser
2 Asked on February 6, 2021
0 Asked on February 6, 2021
1 Asked on February 5, 2021 by jason-vondersmith
2 Asked on February 5, 2021 by farhad-zamani
3 Asked on February 5, 2021
1 Asked on February 5, 2021 by emad-omar
1 Asked on February 5, 2021
1 Asked on February 5, 2021 by marc-rasmussen
3 Asked on February 5, 2021 by ahmed-nagi
3 Asked on February 4, 2021 by aditya-sadhukhan
1 Asked on February 4, 2021 by walterfox
2 Asked on February 4, 2021 by ethan
1 Asked on February 4, 2021 by hari-krishnan
1 Asked on February 4, 2021 by pxaml
2 Asked on February 4, 2021 by fatty_panda
Get help from others!
Recent Questions
Recent Answers
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP