缓存node.js是否可以将输出视为html文件?

时间:2015-04-25 04:00:08

标签: javascript html node.js caching express

在PHP中,我曾经使用output buffering to cache the output并将其保存为html文件。我想知道是否可以在node.js中完成相同的操作。以下是我的路线档案:

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)无效。 console.log(data)在控制台中返回“undefined”,而html文件除了单词“undefined”之外没有任何内容。我也试过这个:

    .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)

    })

仍未定义。有没有办法将视图结果缓存为html文件?

1 个答案:

答案 0 :(得分:1)

在第一个代码段中,dataundefined,因为这是res.render(...)返回的值。

通常(取决于确切的Promise实现),Promise calback中返回的除.then()之外的任何值都将被视为分辨率值。因此,以下2个片段大致相同。

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

要接收html,因为res.render()是异步的并且本身不提供Promise,所以你需要将它包装在Promise中,以便等待:

.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){
    // ...

注意:上述代码段与ES6 Promises兼容,如果您使用其他实施方式,可能需要修改。

对于第二个片段,SO上已经有一个Q& A,有一个很好的解释:

  

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

相关问题