well, in the code you can see that when the first object is saved, the id comes out undefined and then the other objects start to come out fine, I was thinking about it but I can't fix it, the problem is in the save() function in the part that pushes the newProduct does anyone realize what the problem is?
const fs = require("fs");
class Container {
constructor(fileName) {
this.fileName = fileName;
}
async createEmptyFile() {
fs.writeFile(this.fileName, "[]", (error) => {
if (error) {
console.log(error)
} else {
console.log(`File ${this.fileName} was created`);
}
});
}
async readFile() {
try {
const data = await fs.promises.readFile(this.fileName, 'utf-8');
return JSON.parse(data);
} catch (error) {
if (error) {
this.createEmptyFile();
} else {
console.log(`Error Code: ${error} | There was an unexpected error when trying to read ${this.fileName}`);
}
}
}
async save(title, price, thumbnail) {
try {
const data = await this.readFile();
const newProduct = {
title,
price,
thumbnail,
id: data.length + 1
}
data.push(newProduct);
await fs.promises.writeFile(this.fileName, JSON.stringify(data));
return newProduct.id;
} catch (error) {
console.log(`Error Code: ${error.code} | There was an error when trying to save an element`);
}
}
}
const container = new Container("products.json");
const main = async () => {
const id1 = await container.save(
"Regla",
75,
"https://rfmayorista.com.ar/wp-content/uploads/2020/03/REGLA-ECONM_15-CM.-600x600.jpg"
);
const id2 = await container.save(
"Goma",
50,
"https://image.shutterstock.com/image-photo/rubber-eraser-pencil-ink-pen-260nw-656520052.jpg"
);
const id3 = await container.save(
"Lapicera",
100,
"https://aldina.com.ar/wp-content/uploads/2020/08/bic-cristal-trazo-fino-azul-1.jpg"
);
console.log(id1, id2, id3);
};
main();
From already thank you very much
In the readFile method you need to return something on the catch statement in order to get consistent return values
async readFile() {
try {
const data = await fs.promises.readFile(this.fileName, 'utf-8');
return JSON.parse(data);
} catch (error) {
if (error) {
this.createEmptyFile();
} else {
console.log(`Error Code: ${error} | There was an unexpected error when trying to read ${this.fileName}`);
}
// returns [] because this seems to be the default value for the file in createEmptyFile
return []; // Add this line
}
}
What happens is practice is: the file doesn't exist, the try statement fails, then the catch statement and the function don't return anything thus undefined.