1

I was just wondering how to add(push) data into an array via an express router endpoint. Suppose I have an array inside data/data.js directory and my router code look 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;

When I involve POST method in the endpoint of my route then it push the new data and response with an updated array. But when I check my express file then it still the old array. Why I lost the data?
I heartily thank if anyone helps me to figure out this.


As @Aditya toke and @Andre Nuechter suggested I update my code like this:
.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 exit');
        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 didnot contain product information');
      err.status = 404;
      return next(err);
    }
  });

But it pushes the new data like this:

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"}

Which is not what I want. Is there any way to add this to the products array? Or any better approach?

falamiw
  • 426
  • 4
  • 16
  • Does this answer your question? [How to append to a file in Node?](https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node) – goto May 26 '20 at 18:26
  • [Append a new object to an array in a JSON file](https://stackoverflow.com/questions/66817898/append-a-new-object-to-an-array-in-a-json-file/66818970#66818970) may help. – ggorlen Mar 26 '21 at 14:54

2 Answers2

1

The data is lost, because push does not alter the file on your disk. To do that you need to use something like fs.writeFile.

Andre Nuechter
  • 2,141
  • 11
  • 19
1

As you mention about the saving data in the file, that is only possible by using the filesystem to write data in the file,
I would recommend using the JSON extension file, as it's easy to parse and read.
You have to use the filesystem to write data in the file.
And to add further it can be utilised as a global variable all over the project.
There are multiple ways to play with the filesystem using node js.
https://nodejs.org/api/fs.html

Updated The Answer

@falamiw Follow these steps
1. Don't use data.js start using data.json
Structure inside data.json will be like 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"}
          ]
}

Code to make changes in this JSON file

 const fs = require('fs');
    let rawdata = fs.readFileSync('data.json');
   let productArray = JSON.parse(rawdata);
  // push changes to your array
   productArray ['product'].push({ any thing you want to add })
  1. After pushing object inside array now we will make changes in the data.json file using fileSystem.

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

That's it now you can see the changes in the file. I have not tested this code but I am sure it will work you just to debug and check its working.

Aditya toke
  • 461
  • 4
  • 14
  • I didn't use json before. It will be helpful if you give a json like data structure which fit my condition. Thanks @Aditya toke – falamiw May 26 '20 at 19:21
  • @falamiw please confirm the structure of data you wanted. Product : [ { any thing }, { any thing } ] by this way you will be pushing your data one by one in your product array, am I right ? – Aditya toke May 26 '20 at 19:21
  • I want to add the new product object like `{ "title": "...","imageUrl": "...","id": 6 }` into my products array. – falamiw May 26 '20 at 19:24
  • @falamiw I have updated my answer with each step you can check and I will also suggest you, do little RND related to JSON as in most API are written and dealing with JSON format – Aditya toke May 26 '20 at 19:42
  • Thanks. let me try this and let you know is it work or not. I will accept your answer if it works – falamiw May 26 '20 at 19:45
  • @falamiw ya sure do let me know if you got any major issue and you cant fix it out – Aditya toke May 26 '20 at 19:47