为什么我的胡子“文件到字符串”转换抛出一个未定义的异常?

时间:2018-02-14 14:26:33

标签: node.js exception mustache

我是服务器端javascript的新手。我想在Visual Studio Code(1.20.0)中使用node.js(v8.9.4)和mustache.js创建我的第一个测试网站并遇到问题。当我运行我的main.js并尝试访问该站点时,第31行的data.toString('utf8')语句引发了“未定义”异常。但是当我调试它时,它被定义为它应该是缓冲区并正确显示。

我有限的知识使我无法找到原因或至少提示。因此,如果您能解决我的问题,我将不胜感激。非常感谢你。

var mustache = require('mustache');

var model = 
{
    title: 'Mustache', 
    messages: 
    [
        'Mustache is a handy templating language.'
      , 'It goes well with JavaScript.'
      , 'It also goes well with Node.js.'
      , 'It even goes well with Scala!'
      , 'Here it\'s used to generate server-side HTML.'
    ]
}

var http = require('http');
var port = 8081;
var fs   = require('fs');

var server = http.createServer(function (req, res) 
{
    res.writeHead(200, {'Content-Type': 'text/html'});
    function respond(html) 
    {
        res.write(html);
        res.end();
    }

    fs.readFile('template.mustache', function(err, data)
    {
        var template = data.toString('utf8');
        var html = mustache.to_html(template, model);
        respond(html);
    });
})

server.listen(port);
console.log("Server listens: 127.0.0.1:" + port);

我的胡子模板:

<h1>{{title}}</h1>
<ul>{{#messages}}<li>{{.}}</li>{{/messages}}</ul>

0 个答案:

没有答案