Passing an array to jade rendering

So, I have a node.js server where I use express, and I am trying to pass an array to jade rendering.

Code in node.js:

router.get('/render', function(req, res) {
    var t;
    var combo = {'items': []};

    fs.readFile('ek.txt', function(err, data){
        if(err) {
            return console.error("Error: " + err);
        }

        t = data.toString();

        combo.items = t.split(" ");
        combo.items.pop(); //delete last element which is \r\n
        console.log(combo.items);
    });

    res.render('register', {'items': combo.items}, function(err, html) {
        if(err)
            console.log(err);
        else
            res.send(html);
    });
});

And here is the jade code:

select
    -console.log(items); 
    each item in items
      option= item

This should fill my selection in HTML, but it is empty.

Any help would be appreciated!

+4
source share
1 answer

This is the right way to do this, but the problem is that it fs.readFileis asynchronous. So what happens is you create an empty array (because the file has not yet been read).

Possible Solution:

fs.readFile('ek.txt', function(err, data){
    if(err) {
        return console.error("Error: " + err);
    }

    t = data.toString();

    combo.items = t.split(" ");
    combo.items.pop(); //delete last element which is \r\n
    console.log(combo.items);

    res.render('register', {'items': combo.items}, function(err, html) {
        if(err)
            console.log(err);
        else
            res.send(html);
    });
});

Or instead of nesting, you can use promises.

0
source

All Articles