How do I render an EJS template file in Node.js?

前端 未结 8 1753
臣服心动
臣服心动 2020-12-05 05:24

I\'m using Node.js and trying to render an EJS template file. I figured out how to render strings:

    var http = requ         


        
8条回答
  •  猫巷女王i
    2020-12-05 06:05

    There's a synchronous version of this pattern that tightens it up a little more.

    var server = http.createServer(function(req, res) {
        var filePath = __dirname + '/sample.html';
        var template = fs.readFileSync(filePath, 'utf8');
        res.end(ejs.render(template,{}));
    });
    

    Note the use of readFileSync(). If you specify the encoding (utf8 here), the function returns a string containing your template.

提交回复
热议问题