2012-04-21 6 views
2

저는이 전체 node.js 사업에 뛰어 들고 있습니다. 그러나 나는 connect/mustach와 관련된 문제에 부딪쳤다.콧수염 템플릿을 사용하는 빈 출력, connect & 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 -variable을 기록하는 경우 variable 텍스트가 첨부 된 html의 두 출력을 얻으므로 to_html -function이 해당 작업을 수행하는 것 같습니다. 그리고 내가 할 경우 res.end('some string'); 문자열이 브라우저에 표시됩니다.

템플릿은 본문에 <p>{{variable}}</p> 태그가있는 일반 오래된 .html 파일입니다.

어떤 아이디어가 잘못 되었나요?

답변

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.'
(오용 ') 아 거기 당신은 그것이 가지고

+0

을; 그리고 물론, 이제는 당신이 그것을 언급 했으므로, 그 잘못이 있었던 날처럼 명확합니다. 그것을 지적 주셔서 감사합니다! – Erik