putting a fresh item into an array within a JavaScript file on Node.js

I've been trying to figure out how to insert data into an array through an express router endpoint. Let's say I have an array located inside the data/data.js directory and my router code looks something like this:

const express = require('express');
const bodyParser = require('body-parser');
const productRouter = express.Router();
//! bring data
const { products } = require('../data/data');
productRouter.use(bodyParser.json());

productRouter
  .route('/')
  .post((req, res, next) => {
    if (req.body !== null) {
     //some logic
      } else {
        products.push(req.body);
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(products);
      }
    } else {
      //handle error
    }
  });
module.exports = productRouter;

After using the POST method in the route endpoint, it adds the new data and responds with an updated array. However, when I check my express file, it still shows the old array. Why is the new data not being retained?
I would greatly appreciate any help in resolving this issue.


Following suggestions from @Aditya and @Andre Nuechter, I made some updates to my code:

.post((req, res, next) => {
    if (req.body !== null) {
      if (products.some((product) => product.id === req.body.id)) {
        err = new Error('Product with id:' + req.body.id + ' already exists');
        err.status = 404;
        return next(err);
      } else {
        const data_path = path.join(__dirname, '../data/data.js');
        fs.appendFileSync(data_path, JSON.stringify(req.body));
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(products);
      }
    } else {
      err = new Error('Body does not contain product information');
      err.status = 404;
      return next(err);
    }
  });

However, this results in adding the new data as shown below:

exports.products = [
  {
    title: 'camera',
    imageUrl: 'https://source.unsplash.com/gGgoDJRD2WM/300x300',
    id: 1,
  },
...
]
exports.orders = [];
{"title":"mens","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"6"}

This is not the desired output. Is there a way to add this to the products array or perhaps a better approach to achieve this?

Answer №1

When it comes to saving data in a file, the best way is utilizing the filesystem to write data into the file.
For this purpose, I highly recommend using the JSON extension file as it's simple to parse and read.
Moreover, by using the filesystem, you can access the data stored in the file globally across the entire project.
There are various techniques to interact with the filesystem using node js.
https://nodejs.org/api/fs.html

The Answer Update:

@falamiw Here are some steps to follow:
1. Instead of data.js, switch to using data.json
The structure inside data.json should resemble this:

{
products : [
  {"title":"mens","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"6"},
  {"title":"women","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"7"}
          ]
}

To update this JSON file, use the following code snippet:

 const fs = require('fs');
    let rawdata = fs.readFileSync('data.json');
   let productArray = JSON.parse(rawdata);
  // add new data to your array
   productArray ['product'].push({ any thing you want to add })
  1. After appending an object to the array, proceed to update the data.json file using the FileSystem module.

    let data = JSON.stringify(productArray );
    fs.writeFileSync('data.json', data);
    

That's all! You should now observe the changes in the file. While I have not personally tested this code, I believe it will function correctly - simply debug and verify its functionality.

Answer №2

In order to permanently save changes, you must utilize methods like fs.writeFile, as the push method does not directly alter the file on your disk resulting in data loss.

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

Attempting to programmatically enlarge various div elements using a single function

I am attempting to create a script that allows me to dynamically expand and collapse multiple divs using the same code... The expansion and collapse are triggered by clicking on a span element, and I am aiming to target the next adjacent ID (the div that ...

Utilize JavaScript code from an npm package to incorporate its functionality within your program

I have recently integrated the htmlhint library into my development workflow. I am able to execute it via the command line on any HTML file using the following command: npx htmlhint src/test-file.html Upon running this command, the file is linted and any ...

The button remains active in Internet Explorer 10 and cannot be disabled

The button has been specified as <input type="button" id="disable" disabled="disabled" value="Upload" /> However, the appearance of the button does not show it as disabled in Chrome, Firefox, and Safari. Additionally, in Internet Explorer, the bu ...

What is the correct way to retrieve a response from an async/await function?

After working with async/await functions for a few months, I have managed to get my code functioning. However, there are still some aspects of it that elude me, and I could benefit from some guidance. Within the code snippet below lies an async function t ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

Assurance of retrieving information

I am looking to extract specific information from the following website . I have implemented Promises in order to retrieve data about planets, then films associated with a particular planet object. My next goal is to access data within the species array ne ...

Conducting simultaneous tests on the mobile application and web browser to ensure optimal performance

Dear friends, I am in need of some assistance. I am looking to run end-to-end tests simultaneously on a mobile app and a web browser, make alterations on one platform, and check to see the changes reflected on the other multiple times. My current plan is t ...

Constructing the necessary gulp configuration file

When using Gulp and Gulp-sass, with the use of 'gulp.watch', how can I retrieve the directory name of the modified item on the watchlist in order to compile the sass to css? Currently, the setup only compiles the sass files from theme 1. If ther ...

Next.js Configuration Files Explained

Currently, my application is functioning well with the use of Next.js and Next.js API tool for handling requests. The backend is managed through sanity.io which is working smoothly. In my sanity configuration setup, I have a dedicated file named 'san ...

Tips for executing a SOAP request using NodeJs

Despite my efforts in researching various blogs, tutorials, and videos, I still can't find a clear answer on how to execute a RESTful request. For example, in NodeJs, you would code the request, hit the route (https://localhost/3000/api/getStudent), a ...

What are some methods to conceal an email address using Javascript?

let user = 'alex'; let domain = 'gmail.com'; let send = 'msg'; document.getElementById("email").href = "ma" + send + "ilto:" + user + "@" + domain; <a id="email"> <img src="imgs/pic.jpg"> </a> I have been w ...

Troubleshooting steps for resolving a node.js error during execution

I recently delved into server side programming with node.js, but I'm encountering some issues when trying to execute it. My server is set up at 127.0.0.1:80, however, I keep running into errors. Console: Server running at http://127.0.0.1:80/ node:ev ...

Sending emails to multiple recipients with different content using Nodemailer

I have been working on a method to send emails to multiple recipients while also passing the user attribute, which contains the name of the recipient, to the html template. (I AM UTILIZING NODEMAILER as a nodejs module) My current code looks like this: S ...

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

Troubleshooting: JavaScript Bookmarklet Fails to Execute on Certain Websites

Recently, I created a unique bookmarklet that functions flawlessly on some websites, but unfortunately fails to work on others. Interestingly, even when it doesn't work, the script is still added to the bottom of the page; however, only a portion of t ...

Unchecking an available item observable in Knockout.js when clicking on a selected item

When you click on the elements in the top list, a selection is made. If you click on the elements in the bottom list, it will be removed from the list. However, the checkbox in the top list is not being unchecked. How can this issue be resolved? functio ...

The jQuery function for $(window).scroll is not functioning as expected

My challenge is getting the scroll to reveal my scrollTop value I've been working with this code: $(document).ready(function(){ console.log('Hello!'); $(window).scroll(function(){ console.log('Scrolling...'); var wScroll = ...

What is the best way to extract a single item from an array in Javascript and assign it to a different variable

I am currently dealing with an array of objects structured like this: contacts: [ { id: 1, name: "John Doe", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066c696e6846616b676f6a2865696b">[emai ...

Finding the current div based on the scrolling position can be achieved without the use of jQuery

Seeking assistance with a coding challenge. I have a solution in jQuery, but we require the solution in plain JavaScript or Angular. It seems like something is missing. Take a look at this fiddle. The objective is to highlight the corresponding left panel ...