Home > Mobile >  Node.js Express show a Json file with Class Method
Node.js Express show a Json file with Class Method

Time:05-03

Just started with node.js and express and i was trying to show a json file containing an array of 3 objects with a class method

Here is the Class structure

const fs = require('fs')

class GrupoArchivo {
    constructor(ruta) {
        this.ruta = ruta
        this.productos = []
    }

    _leer() {
        return fs.promises.readFile(this.ruta, 'utf-8')
            .then(texto => {
                const productosComoArray = JSON.parse(texto)
                this.productos = productosComoArray
            })
    }

    async obtenerTodas() {
        await this._leer()
        return [...this.productos]
    }

}

module.exports = GrupoArchivo

And here is the Js file with the express server

With the second "app.get" i was trying to get the method showing the json file with no luck

const express = require("express");
const GrupoArchivo = require('./GrupoArchivo.js')

const path = require("path");
const app = express();


app.get("/", (req, res)=>{
    res.sendFile(path.join(__dirname   "/index.html"))
})

const grupo = new GrupoArchivo('./productos.json')

app.get("/productos", (req, res)=>
    res.json(grupo.obtenerTodas()) //this returned me an {}
)

app.listen(8080, ()=>{
    console.log("server listening on port", 8080)
})

CodePudding user response:

All async functions return a promise, so when you call it, you have to use await or .then() to get the resolved value from that promise. You can add async and await like this:

app.get("/productos", async (req, res) => {
    try {
        res.json(await grupo.obtenerTodas());
    } catch(e) {
        console.log(e);
        res.sendStatus(500);
    }
});

Note, this also adds error handling so you can catch any errors from grupo.obtenerTodas().

  • Related