At this point, I feel like I have no other option. Everything appears to be correct from my perspective. However, nothing seems to be working.
I decided to create a small food app for myself to keep track of what I'm eating. I set up a JSON file named foods.json
to store the food items that I input through the app. I have experience doing this in PHP before, which was relatively straightforward. But tackling this task with JavaScript is proving to be quite challenging.
I've tried several different approaches that I found on Google, but none of them have provided a working solution.
Where could the issue be?
function addFood() {
const foodName = document.getElementById('food-name').value;
const foodProt = document.getElementById('food-prot').value;
const foodBadFat = document.getElementById('food-badfat').value;
const foodFat = document.getElementById('food-fat').value;
const foodCarbs = document.getElementById('food-carbs').value;
const foodSalt = document.getElementById('food-salt').value;
var jsonArray = '{"name": "' + foodName + '","prot": '+ foodProt + ',"badfat": ' + foodBadFat + ',"fat": ' + foodFat + ',"carbs": ' + foodCarbs + ',"salt": ' + foodSalt + '}';
const fs = require("fs");
let foodList = fs.readFileSync("../json/foods.json","utf-8"); // Read JSON file
let foods = JSON.parse(foodList); // JSON file -> Array
foods.push(jsonArray); // Add object jsonArray to array foods
foodList = JSON.stringify(foods); // Array back to JSON
fs.writeFileSync("../json/foods.json", foodList, "utf-8"); // Save modified JSON file
}