如何根据请求编译jade而不仅仅是服务器启动?

时间:2013-04-02 17:25:20

标签: javascript node.js pug

我希望在服务器请求/响应上编译我的jade,这样我就可以对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.');

我希望自己清楚明白!

1 个答案:

答案 0 :(得分: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);
    });
}