带胡子模板的空白输出,connect&node.js
我刚刚进入这个完整的node.js业务,并喜欢它; 不过,我遇到了一个涉及connect / mustach的问题。
这是简单的一个页面应用程序的代码; 在这一点上,我真的只是想让应用程序使用我的小胡子模板,以便我可以从那里拿走它。
var connect = require("connect"), fs = require("fs"), mustache = require("mustache"); connect( connect.static(__dirname + '/public'), connect.bodyParser(), function(req, res){ var data = { variable: 'Some text that I'd like to see printed out. Should in the long run come from DB.' }, htmlFile = fs.createReadStream( __dirname + "/views/index.html", { encoding: "utf8" } ), template = "", html; htmlFile.on("data", function(data){ template += data; }); htmlFile.on("end", function(){ html = mustache.to_html(template, data); }) res.end(html); } ).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
我的问题在于,上面的代码生成一个空白的网页。 如果我login的html
variables我得到两个输出的HTML与附加的variable
文本,所以to_html
function似乎做它的工作。 如果我做res.end('some string');
该string显示在浏览器中,因为它应该。
该模板是一个普通的.html文件,在它的正文中有一个<p>{{variable}}</p>
标签。
任何想法有什么不对?
你的问题是你没有正确使用asynchronous代码。 在res.end(html)
被调用的时候,文件还没有被读取。 正确的用法:
htmlFile.on("end", function(){ html = mustache.to_html(template, data); res.end(html); })
你也应该注意语法错误: variable: 'Some text that I'd like to see printed out. Should in the long run come from DB.'
variable: 'Some text that I'd like to see printed out. Should in the long run come from DB.'
(滥用')