在 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/