I'm just getting into this whole node.js business and like it so far; however I've run into an issue involving connect/mustach.
Here's the code for a simple one page app; at this point I'm really just trying to get the app to use my mustache templates so that I can take it from there.
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/');
My problem here is that the above code generates a blank webpage.
If I log the html
-variable I get two outputs of the html with the variable
text attached in it, so the to_html
-function seems to do it's job. And if I do res.end('some string');
the string is displayed in the browser as it should.
The template is a plain old .html-file with a <p>{{variable}}</p>
-tag in its body.
Any idea what's wrong?
Your problem is that you're not using async code correctly. By the time res.end(html)
gets called the file is not yet read. Correct usage:
htmlFile.on("end", function(){
html = mustache.to_html(template, data);
res.end(html);
})
Also you should take care of the syntax error: variable: 'Some text that I'd like to see printed out. Should in the long run come from DB.'
(misuse of ')