0

In PHP, I used to use output buffering to cache the output and save it as a html file. I was wondering if the same could be done in node.js. The following is my route file:

module.exports = {

 index: function(section,page,req,res){
  var l = res.locals,  

  db = l.db,

  Promise = l.Promise,

  Promise.props({

       my: db.db.query('CALL fetchdata()'),

       amba: db.db.query("CALL fetchanother()")
  }).then(function(obj){ 

       return res.render(section+'.html',obj)

    }).then(function(data){

       console.log(data);

       l.fs.writeFile('index.html', data)

    }).catch(function (error) {

       console.log(error);
    })
 }
};

return res.render(section+'.html',obj) isn't working. console.log(data) returns "undefined" in the console and the html file doesn't have anything but the word "undefined". I have also tried this:

    .then(function(obj){ 
       var cache
       res.render(section+'.html',obj,function(k,content){
           res.send(content)
           cache = content
       })
       return cache;
    }).then(function(data){
       console.log(data);
       l.fs.writeFile('index.html', data)

    })

It is still undefined. Is there a way to cache the view result as a html file?

RedGiant
  • 4,444
  • 11
  • 59
  • 146
  • 1
    Note that Express already implements caching of views, though it's typically disabled for development -- [`"view cache"` option](http://expressjs.com/4x/api.html#app.set). – Jonathan Lonowski Apr 25 '15 at 05:57

1 Answers1

1

In the 1st snippet, data is undefined because that's the value that res.render(...) returns.

Typically (depending on the exact Promise implementation), any value other than another Promise returned in a .then() calback will be treated as a resolution value. So, the following 2 snippets are roughly equivalent.

.then(function () {
    return undefined;
})
.then(function () {
    return new Promise(function (resolve) {
        resolve(undefined);
    });
})

To receive the html, since res.render() is asynchronous and doesn't provide a Promise itself, you'll want to wrap it in a Promise so it's waited on:

.then(function(obj){
    return new Promise(function (resolve, reject) {
        res.render(section+'.html', obj, function (err, html) {
            if (err)
                reject(err);
            else
                resolve(html);
        });
    });
}).then(function(data){
    // ...

Note: The above snippets are compatible with ES6 Promises and may require revisions if you're using a different implementation.


For the 2nd snippet, there's already a Q&A on SO with a good explanation:

Why is my variable unaltered after I modify it inside of a function?

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199