0

Now I dont have any other choise. Everything seems right in my eye. Still not working.

I am doing little food app for myself to get know how much i've eaten. I created JSON file named ruoat.json, where I going to add foods via app. I have done this earlier with PHP and it was quite easy. But now doing this with JavaScript gives me a gray hair.

Tried few different ways find from Google, no any working solution.

Where is the problem?

function addfood() {

    const food_name = document.getElementById('food-name').value;
    const food_prot = document.getElementById('food-prot').value;
    const food_badfat = document.getElementById('food-badfat').value;
    const food_fat = document.getElementById('food-fat').value;
    const food_carbs = document.getElementById('food-carbs').value;
    const food_salt = document.getElementById('food-salt').value;


    var json_array = '{"name": "' + food_name + '","prot": '+ food_prot + ',"badfat": ' + food_badfat + ',"fat": ' + food_fat + ',"carbs": ' + food_carbs + ',"salt": ' + food_salt + '}';

    // var json_push = JSON.parse(json_array); // Muuntaa stringin JSON objektiksi


    const fs = require("fs");
    let ruokalista = fs.readFileSync("../json/ruoat.json","utf-8"); // Read JSON file

    let ruoka = JSON.parse(ruokalista); // JSON file -> Array

    ruoka.push(json_array); // Add object json_array to array ruoka

    ruokalista = JSON.stringify(ruoka); // Array back to JSON

    fs.writeFileSync("../json/ruoat.json",ruokalista,"utf-8"); // Save modified JSON file

}
2
  • 1
    1. Do not manually build JSON strings 2. json_array is not an array Commented Nov 3, 2020 at 12:26
  • 1
    You can not access to a file using JS inside browser. Commented Nov 3, 2020 at 12:29

1 Answer 1

1

I can see that you are using the fs module, which is a part of Node.js. Nodejs does not support the document object because it is designed to be run outside a browser. That aside, it would work if you didn't do the file business and ran it in a browser

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.