javascript - Is it possible cache node.js view output as a html file? -
in php, used use output buffering cache output , save html file. wondering if same done in node.js. following 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 console , html file doesn't have word "undefined". have 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 still undefined. there way cache view result html file?
in 1st snippet, data
undefined
because that's value res.render(...)
returns.
typically (depending on exact promise implementation), value other promise
returned in .then()
calback treated resolution value. so, following 2 snippets equivalent.
.then(function () { return undefined; })
.then(function () { return new promise(function (resolve) { resolve(undefined); }); })
to receive html
, since res.render()
asynchronous , doesn't provide promise itself, you'll want wrap in promise 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: above snippets compatible es6 promises , may require revisions if you're using different implementation.
for 2nd snippet, there's q&a on explanation:
Comments
Post a Comment