我刚刚进入整个 Node.js 业务并且到目前为止很喜欢它;但是我遇到了涉及 connect/mustach 的问题。
这是一个简单的单页应用程序的代码;此时,我实际上只是想让应用程序使用我的 mustache 模板,以便我可以从那里获取它。
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 的两个输出 variable
其中附有文本,因此 to_html
- 功能似乎可以完成它的工作。如果我这样做res.end('some string');
该字符串按其应有的方式显示在浏览器中。
该模板是一个普通的旧 .html 文件,带有 <p>{{variable}}</p>
- 正文中的标签。
知道出了什么问题吗?
最佳答案
您的问题是您没有正确使用异步代码。当 res.end(html)
被调用时,文件还没有被读取。正确用法:
htmlFile.on("end", function(){
html = mustache.to_html(template, data);
res.end(html);
})
此外,您还应该注意语法错误:变量:'我希望看到打印出来的一些文本。从长远来看应该来自数据库。'
(误用')
关于node.js - 带有 Mustache 模板、connect 和 node.js 的空白输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10259130/