我刚刚进入整个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/');
我的问题是上面的代码会生成一个空白网页。
如果我记录html
- 变量,我会得到两个带有variable
文本的html输出,因此to_html
- 函数似乎可以完成它的工作。如果我res.end('some string');
,则字符串会在浏览器中显示。
该模板是一个普通的.html文件,其正文中包含<p>{{variable}}</p>
标记。
知道什么是错的吗?
答案 0 :(得分:2)
您的问题是您没有正确使用异步代码。到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.'
(滥用')