渲染静态html时出错

时间:2012-02-23 01:53:21

标签: node.js express ejs

此代码:

var app = require('express').createServer();
var ejs = require('ejs');
var fs = require('fs');
var indexTemplate = fs.readFileSync(__dirname + '/templates/index.html');

app.get('/', function(req, res){
    res.end(ejs.render(indexTemplate, {}));
});

给我以下错误

  

TypeError:对象地址                没有方法'substr'       at Object.parse(/home/lowerkey/node_modules/ejs/lib/ejs.js:152:20)       at /home/lowerkey/node_modules/ejs/lib/ejs.js:192:13       在Object.render(/home/lowerkey/node_modules/ejs/lib/ejs.js:35:10)       at / home / lowerkey / workspace / address book / server / server.js:60:14       在回调(/home/lowerkey/node_modules/express/lib/router/index.js:272:11)       在param(/home/lowerkey/node_modules/express/lib/router/index.js:246:11)       在通过(/home/lowerkey/node_modules/express/lib/router/index.js:253:5)       在Router._dispatch(/home/lowerkey/node_modules/express/lib/router/index.js:280:4)       在Object.handle(/home/lowerkey/node_modules/express/lib/router/index.js:45:10)       在下一个(/home/lowerkey/node_modules/express/node_modules/connect/lib/http.js:203:15)

我做错了什么?

1 个答案:

答案 0 :(得分:6)

由于readFile返回值的默认编码,您的 indexTemplate 变量实际上包含缓冲区而不是字符串。您可能需要尝试在 readFileSync 第二个参数中添加编码进行设置,如下所示:

...
var indexTemplate = fs.readFileSync(__dirname + '/templates/index.html', 'utf8');
...