【发布时间】:2021-10-11 21:07:27
【问题描述】:
我正在使用节点 js 并尝试将一组 JSON 数据保存到文件中。
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);
});
});
但是 JSON 数据是以嵌套方式保存在文件中的。
[
[
[
{
"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"
}
]
在这种情况下我该怎么办?
编辑:
这是来自我的班级建设者
constructor(title, imageUrl, description, price) {
this.title = title;
this.imageUrl = imageUrl;
this.description = description;
this.price = price;
}
我尝试过这样的 concat
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);
});
});
但是得到一个空数组
[
[
{
"title": "",
"imageUrl": "",
"description": "",
"price": ""
}
]
]
【问题讨论】:
-
data和this变量的值是多少?在将products变量写入文件之前,它的值是多少?尝试添加一些 console.logs。