2013-04-02 31 views
0

我正在尋找在服務器請求/響應上編譯我的翡翠,這樣我可以對玉文件進行更改並實時查看,而不必每次都重新啓動服務器。這是迄今爲止的假模型。如何根據請求編譯jade而不僅僅是服務器啓動?

var http = require('http') 
    , jade = require('jade') 
    , path = __dirname + '/index.jade' 
    , str = require('fs').readFileSync(path, 'utf8'); 


    function onRequest(req, res) { 
     req({ 
      var fn = jade.compile(str, { filename: path, pretty: true}); 
     }); 
     res.writeHead(200, { 
      "Content-Type": "text/html" 
     }); 

     res.write(fn()); 
     res.end(); 
    } 

http.createServer(onRequest).listen(4000); 
console.log('Server started.'); 

我希望我明白了!

+0

什麼exactely是問題嗎?你的方法看起來很有前途...... –

+0

最初我有'var fn = jade.compile(str,{filename:path,pretty:true});'在頂部,但只有在服務器啓動時才運行一次。因此,如果我要對我的玉石模板進行更改,我必須手動停止並啓動服務器才能看到真正煩人的更改。我希望它在每次請求服務器時都創建該變量 – Datsik

回答

0

您只在服務器啓動時讀取一次文件。如果你想擁有它讀取的變化,你不得不看它的要求,這意味着你的實體模型看起來更象:

function onRequest(req, res) { 
    res.writeHead(200, { 
     "Content-Type": "text/html" 
    }); 

    fs.readFile(path, 'utf8', function (err, str) { 
     var fn = jade.compile(str, { filename: path, pretty: true}); 
     res.write(fn()); 
     res.end(); 
    }); 
} 

類似的東西會每次讀取的文件,這是可能是好的開發的目的,但如果你只有想更改/處理文件,你可能會使用文件觀察器(fs.watch可能適合此法案)。

像這樣(只是一個未經測試的例子作爲一個想法):

var fn; 

// Clear the fn when the file is changed 
// (I don't have much experience with `watch`, so you might want to 
// respond differently depending on the event triggered) 
fs.watch(path, function (event) { 
    fn = null; 
}); 

function onRequest(req, res) { 
    res.writeHead(200, { 
     "Content-Type": "text/html" 
    }); 

    var end = function (tmpl) { 
     res.write(tmpl()); 
     res.end(); 
    }; 

    if (fn) return end(fn); 

    fs.readFile(path, 'utf8', function (err, str) { 
     fn = jade.compile(str, { filename: path, pretty: true}); 
     end(fn); 
    }); 
} 
相關問題