2

我刚刚进入整个 node.js 业务并且到目前为止喜欢它;但是我遇到了一个涉及连接/胡子的问题。

这是一个简单的单页应用程序的代码;在这一点上,我真的只是想让应用程序使用我的小胡子模板,以便我可以从那里获取它。

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- 变量,我会得到两个带有附加文本的 html 输出variable,所以to_html- 函数似乎可以完成它的工作。如果我这样做res.end('some string');,字符串会按原样显示在浏览器中。

该模板是一个普通的旧 .html 文件,其正文中带有<p>{{variable}}</p>-tag。

知道有什么问题吗?

4

1 回答 1

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.'
误用')

于 2012-04-21T13:54:10.367 回答