JSjohn
JSjohn

Reputation: 77

Render JSON data onto ejs view with Expressjs

I am trying to get 2 values from a JSON file on to the webpage. obj["fruit"] and obj["thyroid"]. I use ejs as the template view engine and expressjs.

The below method says "fruit" and "thyroid" are undefined. The console.log works though.

app.post('/top', function (req, res) {
    var obj;
    fs.readFile('./object.json', 'utf8', function (err, data) {
        if (err) throw err;
        obj = JSON.parse(data);
        console.log(obj["fruit"]);
        console.log(obj["thyroid"]);

    });
    res.render(
        'disp.ejs',
        { 
            food: obj["fruit"]
            name: obj["thyroid"]

        }); // render
});

Upvotes: 0

Views: 1417

Answers (1)

Andrew L
Andrew L

Reputation: 5486

fs.readFile(path[, options], callback) is the asynchronous way to read a file. The way your code is setup node will start reading the file and immediately then call res.render before the file data is finished reading.

If you put the res.render inside the callback it will only be called when the file is finished reading and the data variable has what you need.

for example:

app.post('/top', function (req, res) {
    var obj;
    fs.readFile('./object.json', 'utf8', function (err, data) {
        if (err) throw err;
        obj = JSON.parse(data);
        console.log(obj["fruit"]);
        console.log(obj["thyroid"]);
        res.render(
          'disp.ejs',
          { 
            food: obj["fruit"]
            name: obj["thyroid"]

          }); // render
    });
});

Upvotes: 1

Related Questions