So basically, I'm working on this project for frontendmentor and I wanted to go a bit further and make it so this shows stored tasks as well as add new ones.
// JSON.data
[
{
"name": "task1",
"todo": "Complete online Javascript course"
},
{
"name": "task2",
"todo": "Jog around the park 3x"
}
]
// Script
getData = () => {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status ==200) {
const myData = JSON.parse(this.responseText)
dataUse(myData)
saveData(myData)
}
}
xhttp.open("GET", "data.json", true);
xhttp.send();
}
dataUse = (object) =>{
object.forEach((datas)=>{
const todo = document.createElement('div')
todos.appendChild(todo)
const input = document.createElement('input')
input.setAttribute('type', 'checkbox')
input.setAttribute('id', datas.name)
input.setAttribute('class', 'checks')
todo.appendChild(input)
const label = document.createElement('label')
label.setAttribute('for', datas.name)
label.setAttribute('class', `${datas.name} tasks`)
todo.appendChild(label)
const span = document.createElement('span')
label.appendChild(span)
const paragraph = document.createElement('p')
paragraph.innerHTML = datas.todo
label.appendChild(paragraph)
})
}
getData()
Currently the code above loads the data and then proceeds to make the element needed and place the info in the right place.
What I need now is to make it so it saves a new object to JSON file (when the input has a value(I think I can figure this part myself)) automatically and then proceeds to show it just like the dataUse function does. This is what I tried to do:
let newData = {
name: "task3",
todo: "Water the plants"
}
const fs = require('fs')
const saveData = (object) =>{
const finished = (error)=>{
if(error){
console.error(error);
return
}
}
object.push(newData)
const jsonData = JSON.stringify(object, null, 2)
fs.writeFile('data.json', jsonData, finished)
}
This doesn't seem to work but when I try pushing the newData without attempting to rewrite the file and console.log it it does show all the objects including the new one. So how do I make this work? or is there a better way to do this?
I think what you are looking for is fs.appendFile
fs.appendFile("data.json", jsonData, finished);
I have a repo that uses this general format for reference: https://github.com/cireneirbo/iCanRead-iCanWrite-imFS/blob/main/main.js