代码上的Javascript Mustache无效模板

时间:2017-05-11 12:11:43

标签: javascript node.js mustache

我正在处理一个应用程序,我已经通过npm安装了小胡子。

然后在我的main.js文件中我导入了它:

const Mustache = require('mustache')

然后我有一个html模板文件:

<title>{{ title }}</title>在html文件的tile部分。

使用节点我然后加载模板文件并尝试运行渲染。

以下是代码:

fs.readFile('template.html', (err, data) => {

  var mydata = Mustache.render(data, {title: "sometitle"});

  fs.writeFile('result.html', mydata, (err) => {

    if (err) throw err;
    console.log('The file has been saved!');

  });

}); 

我一直收到这个错误:

TypeError:模板无效!模板应该是一个“字符串”,但“对象”是作为胡子的第一个参数#grave

如何解决此问题,以便我可以更改并保存结果?

1 个答案:

答案 0 :(得分:1)

正如您在此处所见:node doc如果您未指定编码,则回调将接收原始缓冲区;如果你想要一个字符串只需添加一个编码(让我们说它是UTF-8文件):

fs.readFile('template.html', 'utf8', (err, data) => {
  var mydata = Mustache.render(data, {title: "sometitle"});
  fs.writeFile('result.html', mydata, (err) => {
    if (err) throw err;
      console.log('The file has been saved!');
  });
});