Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
I need help the first object is saved undefined

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda