res.render在调用fs.stat / fs.access后导致本机错误

时间:2015-11-05 05:55:38

标签: node.js express fs

我试图为我的网站的一个子集构建一个包含所有路由,包含需要由ejs处理的多个目录/页面,但不需要特定的路由。

[注意,我在下面的例子中包含同步版本以删除任何时间问题...... fs.stat(和fs.access)的类似实现会导致相同的行为]

router.get('/foobar/:page(*)', function(req, res, next) {

    var fs = require('fs');
    var path = require('path');
    var viewsPath = req.app.get('views');

    try
    {
        // see if there's an ejs file corresponding to request
        var stats = fs.statSync(path.join(viewsPath, 'foobar', req.params.page + '.ejs'));
        console.log(stats);  // stats object seems accurate

        // THROWS WHEN CALLING openSync
        res.render('foobar/' + req.params.page, {title: 'foo'});
    }
    catch (e)
    {
        var err = new Error();
        err.status = 404;
        next(err);
    }
}

404路径工作正常,但当我请求实际存在的页面时,渲染调用抛出:

Unexpected error code undefined has occurred. Please retry your request
    at Error (native)
    at Object.fs.openSync (fs.js:500:18)
    at Object.fs.readFileSync (fs.js:352:15)
    at includeSource (C:\Users\Jim\Documents\myProject\node_modules\ejs\lib\ejs.js:194:17)
    at C:\Users\Jim\Documents\myProject\node_modules\ejs\lib\ejs.js:528:26
    at Array.forEach (native)
    at Object.Template.generateSource (C:\Users\Jim\Documents\myProject\node_modules\ejs\lib\ejs.js:505:15)
    at Object.Template.compile (C:\Users\Jim\Documents\myProject\node_modules\ejs\lib\ejs.js:427:12)
    at Object.compile (C:\Users\Jim\Documents\myProject\node_modules\ejs\lib\ejs.js:288:16)
    at handleCache (C:\Users\Jim\Documents\myProject\node_modules\ejs\lib\ejs.js:147:16)
    at View.exports.renderFile [as engine] (C:\Users\Jim\Documents\myProject\node_modules\ejs\lib\ejs.js:350:14)
    at View.render (C:\Users\Jim\Documents\myProject\node_modules\express\lib\view.js:126:8)
    at tryRender (C:\Users\Jim\Documents\myProject\node_modules\express\lib\application.js:639:10)
    at EventEmitter.render (C:\Users\Jim\Documents\myProject\node_modules\express\lib\application.js:591:3)
    at ServerResponse.render (C:\Users\Jim\Documents\myProject\node_modules\express\lib\response.js:961:7)
    at C:\Users\Jim\Documents\myProject\routes\power-essentials.js:32:7
    at Layer.handle [as handle_request] (C:\Users\Jim\Documents\myProject\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Jim\Documents\myProject\node_modules\express\lib\router\route.js:131:13)
    at Route.dispatch (C:\Users\Jim\Documents\myProject\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Jim\Documents\myProject\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Jim\Documents\myProject\node_modules\express\lib\router\index.js:277:22
    at param (C:\Users\Jim\Documents\myProject\node_modules\express\lib\router\index.js:349:14)

它的行为几乎与fs.statSync调用一样,锁定了在尝试打开视图文件时呈现阻塞的文件。

1 个答案:

答案 0 :(得分:0)

occams razor:我正在使用的测试页面中包含无效的包含路径引用!它并没有抱怨我试图加载的模板,而是在其中引用了一个模板。