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": ""
}
]
]
dataandthisvariable? What is the value of theproductsvariable before you write it to the file? Try to add some console.logs.