0

我希望在服务器请求/响应上编译我的翡翠,这样我就可以对翡翠文件进行更改并实时查看它,而不必每次都重新启动服务器。这是我到目前为止的假模型。

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.');

我希望我说清楚了!

4

1 回答 1

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);
    });
}
于 2013-04-02T18:27:38.260 回答