bueno en el codigo se ve que cuando se guarda el primer objeto sale el id indefinido y despues los demas objetos empiezan a salir bien, lo estuve pensando pero no lo puedo arreglar, el problema esta en el función save () en la parte que empuja el nuevo Producto, ¿alguien se da cuenta de cuál es el problema?
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();Desde ya muchas gracias
En el método readFile , debe devolver algo en la instrucción catch para obtener valores de retorno consistentes
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 } } Lo que sucede es la práctica: el archivo no existe, la declaración de try falla, luego la declaración de catch y la función no devuelven nada por lo tanto undefined .