node.js - 带有 Mustache 模板、connect 和 node.js 的空白输出

标签 node.js mustache node.js-connect

我刚刚进入整个 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/

相关文章:

javascript - 如何在由 Jekyll 和 Liquid Layouts 一起生成的站点中使用 mustache.js

node.js - 在 Express 中,为什么 .config() 中的 env 变量是可选的?

javascript - stub 连接中间件

node.js - Socket.emit 不发送或 socket.on 不接收?

javascript - 如何在委托(delegate)中找到可点击元素的索引?

mysql - 我应该在 Node.js (Express) 应用程序中的什么地方定义我的 MySQL 客户端?

php - 在 Mustache PHP 中访问数组中的数组

javascript - 使用 Connect 上传文件

node.js - 向我的 Jade 模板添加页脚时超出了最大调用堆栈大小

javascript - NodeJS : How to re-display custom CLI menu after executing corresponding functionality