1

I am using node js and trying to save a set of JSON data into file.

const products = [];
    fs.readFile(pathToTheFile, (err, data) => { // get the data from the file
        if(data != ''){
            products.push(JSON.parse(data)); // the data is in string format. convert it into JSON and push into the empty arry of products
        }
        products.push(this); // push the form data in to products array after the file data
        fs.writeFile(pathToTheFile, JSON.stringify(products), (err) => { // convert the products array back into string and update the file entirely with the data
            console.log(err);
        });            
    });

But the JSON data is being saved in the file like this in nested way.

[
[
    [
        {
            "title": "1",
            "imageUrl": "https://images.pexels.com/photos/279906/pexels-photo-279906.jpeg?cs=srgb&dl=pexels-pixabay-279906.jpg&fm=jpg",
            "description": "wer",
            "price": "1234"
        }
    ],
    {
        "title": "2",
        "imageUrl": "https://images.pexels.com/photos/279906/pexels-photo-279906.jpeg?cs=srgb&dl=pexels-pixabay-279906.jpg&fm=jpg",
        "description": "er3t",
        "price": "21345"
    }
],
{
    "title": "3",
    "imageUrl": "https://images.pexels.com/photos/279906/pexels-photo-279906.jpeg?cs=srgb&dl=pexels-pixabay-279906.jpg&fm=jpg",
    "description": "wew",
    "price": "2345"
}

]

What shall I do in this case?

Edit:

The this is coming from my class contructor

    constructor(title, imageUrl, description, price) {
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.price = price;
}

I tried with concat like this

 const products = [];
    fs.readFile(pathToTheFile, (err, data) => { // get the data from the file
        if (data != '') {
            products.push(JSON.parse(data)); // the data is in string format. convert it into JSON and push into the empty arry of products
            //console.log(this);
            products.concat(this);
        } else {
            products.push(this); // push the form data in to products array after the file data
        }
        console.log(products);
        fs.writeFile(pathToTheFile, JSON.stringify(products), (err) => { // convert the products array back into string and update the file entirely with the data
            console.log(err);
        });
    });

But getting an empty array

[
[
    {
        "title": "",
        "imageUrl": "",
        "description": "",
        "price": ""
    }
]

]

1
  • What is the value of the data and this variable? What is the value of the products variable before you write it to the file? Try to add some console.logs. Commented Aug 7, 2021 at 9:20

2 Answers 2

1

You are inserting an array into the product array.
See the correct code below -

const products = [];
    fs.readFile(pathToTheFile, (err, data) => { // get the data from the file
        if(data != ''){
            products = JSON.parse(data);
        }
        products.push(this);
        fs.writeFile(pathToTheFile, JSON.stringify(products), (err) => {
            console.log(err);
        });            
    });
Sign up to request clarification or add additional context in comments.

3 Comments

this one worked. thank you. But I had to change const product = [] to let product =[]. Can you please explain this line? products = JSON.parse(data));
Do you need the products as a global variable? Otherwise, you can use declare products as const inside arrow function.
Never mind. Got it. I was inserting the data. I had to store it.
0

Instead of push() you should use concat() method.

push() : The push() method adds one or more elements to the end of an array and returns the new length of the array. (MDN)

var arr1 = [‘a’, ‘b’, ‘c’];
var arr2 = [‘d’, ‘e’, ‘f’];
var arr3 = arr1.push(arr2);
console.log(arr3); // 4
console.log(arr1); // [“a”,> “b”, “c”, [“d”, “e”, “f”]]

concat() : The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var arr1 = [‘a’, ‘b’, ‘c’];
var arr2 = [‘d’, ‘e’, ‘f’];
var arr3 => arr1.concat(arr2);
console.log(arr3); //[“a”, “b”, “c”, “d”, “e”, “f”]

1 Comment

tried concat. edited the question with my try with concat

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.