JavaScript adding arrays to JSON files

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

}

Answer №1

It appears you are utilizing the fs module, a component of Node.js. The Node.js environment does not incorporate the document object as it is intended for execution outside of a browser. However, if you were to omit the file operations and execute the code within a browser, it should function correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for merging arrays conditionally in JavaScript

Currently facing a dilemma without a clear solution, aiming to provide minimal context and focus solely on the problem at hand A worker logs their daily hours at work, stored in the "dayli_data" array. If the worker misses logging hours, it triggers the " ...

Sending a cookie token to the server through the header

This is my first attempt at working with a server Utilizing React and express Storing token in browser cookie from the server //Upon login request res.cookie('token', token, {maxAge: 3600000} ).json({ user: userDoc, message: 'message!&apos ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

jQuery: Remove the class if it exists, and then assign it to a different element. The power of jQuery

Currently, I am working on a video section that is designed in an accordion style. My main goal right now is to check if a class exists when a user clicks on a specific element. The requirement for this project is to allow only one section to be open at a ...

What steps do I need to take in order to create a histogram with perfect symmetry?

I am looking to create a unique JavaScript program that can generate a symmetric histogram resembling the image provided below: This program will prompt the user to input the number of bars they want to display and specify the character used to draw the b ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

What is the reason for being unable to submit the value of an input that is disabled?

When I try to save the value of an input field that is disabled and has the required attribute, I receive an error message stating that "field_name is required". Why am I unable to insert a value when the input field is disabled? <input disabled type=&q ...

Using React JS to extract query string values

My current URL contains the following: http://example.com/callback?code=abcd I am trying to extract the value of "code." Here is the React code I have written: import React from 'react'; import { useEffect } from 'react'; const Callba ...

The POST function is executed twice, with the first attempt resulting in a failed API call, but the second attempt is

I am experiencing issues with my subscribe dialog, as it seems to be running the API call twice. The first time it fails, but on the second attempt, it succeeds and inserts the email into the database. This double run is causing errors in my AJAX function, ...

Activate and deactivate button

I've tried multiple examples on this site for enabling and disabling a button using javascript with jquery, but none of them seem to work for me. Here is my current dilemma: <asp:TextBox ID="mytext" runat="server" onkeyup="enableButton(this, 3)"/ ...

How can I prevent my mouse click from being overridden by my mouse hover?

Currently, I am developing a Sudoku game using JavaScript and facing some challenges with mouse events. My goal is to enable users to hover over a square and have it change color, as well as click on a square to highlight the entire row, column, and quadra ...

Is it possible to substitute the variables with the function name?

Is there a way to duplicate the variable name? Take a look at the example below (note the name a1) $(document).ready(function() { name = "a1"; // This is "NAME" as a1 }) function name() { // USING "NAME" $("#test" + name).keydown(function(a) ...

Discovering duplicate values in a JSON object using JavaScript (JQuery)

Below is a JSON object that contains information about various materials: [ { "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000", "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)", "uns": "S45000", "temperatura": "NL", "p ...

There was an error because the variable "items" has not been defined

Having some trouble with an AngularJS service where I am attempting to add an item to an array every 5 seconds. However, I keep encountering the error 'items is not defined' after the first dynamic addition... I've been tinkering with this ...

Is a fresh connection established by the MongoDB Node driver for each query?

Review the following code: const mongodb = require('mongodb'); const express = require('express'); const app = express(); let db; const options = {}; mongodb.MongoClient.connect('mongodb://localhost:27017/test', options, fu ...

Create a function that adds a new div element with a one-of-a-kind identification when

I am currently developing a web application on www.firstusadata.com/cash_flow_test/. The functionality involves two buttons that add products and vendors dynamically. However, the issue I'm facing is that the appended divs do not have unique IDs, maki ...

Retrieve the parent node's class using JavaScript without relying on jQuery

Attempting to retrieve the class of the parent node of a selected element using JavaScript, but encountering issues with the following code snippet. Any guidance on what needs to be corrected? function getParentNodeClass() { var parentNodeClass = this.p ...

Ensure that each function is completed before proceeding to the next one

I've encountered an issue with my react app. After a user submits a form, I need a modal to open and the user's response to be stored in state. Then, based on this response, I have to execute some business logic before finally submitting the form ...

JavaScript error: Cannot use `.splice()` on [array] ("Uncaught TypeError: collisions.splice is not a function")

Struggling to remove specific items from an array in javascript, the [array].splice function seems to be causing issues. This piece of code is designed to detect collisions between SVG objects (for a game). The goal is to eliminate 3 objects that the pl ...

What are some ways I can efficiently load large background images on my website, either through lazy loading or pre

Just dipping my toes into the world of javascript. I'm currently tackling the challenge of lazy loading some large background images on my website. My goal is to have a "loading" gif displayed while the image is being loaded, similar to how it works ...