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

标签 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) 在控制台中返回“未定义”,并且 html 文件除了“未定义”一词之外没有任何内容。我也尝试过这个:

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

    })

它仍然是未定义的。有没有办法将 View 结果缓存为html文件?

最佳答案

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

通常(取决于具体的 Promise 实现),除了 .then() 回调中返回的另一个 Promise 之外的任何值都将被视为解析值。因此,以下 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 的问答,并有很好的解释:

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

关于javascript - 是否可以将 node.js View 输出缓存为 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860848/

相关文章:

javascript - Firefox 中的 event.offsetX

javascript - 自学习并尝试返回一个数组,其中每个数字都按提供的增量递增

javascript - img 嵌入式 SVG 在将其转换为内联 SVG 后不会改变颜色

node.js - 将图像转换为多行灰度像素值

node.js - 如何为基于 Express 构建的 REST API 实现 CAS 身份验证

javascript - 对 JS 数组进行分组排序

javascript - 为什么这个 Vuejs "Hello World"示例无法在我的计算机上呈现?

html - 禁用平移移动网站

单击单选按钮时 Javascript 边框颜色不会改变

node.js - 要求 ts-node 和 ts-node/register 有什么区别