Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!