【问题标题】:NODEJS readFile , writeFile and middlewares usage for error casesNODEJS readFile , writeFile 和中间件在错误情况下的使用
【发布时间】:2017-02-23 13:14:02
【问题描述】:
  1. 我要读取文件 xx.txt
  2. 操作数据并写入文件 yy.txt
  3. 所有这些都在使用中间件的 POST() 中,该中间件也需要更新错误,并相应地转移到下一个级别,以便我可以正确回复状态和消息。

我一直看到 - 如果我使用异步模式进行读/写,错误不会在我的 req.output 对象上正确更新(因为它不会等待查看是否有错误),如果我尝试使用readFileSync,它卡住了。 我错过了什么?

    var middle_1 = function (req, res, next) {

        // setup my req.output to transfer data to the next middleware
        req.output = {
            statusCode : 200,
            message : `OK - 200`
        }

        fs.readFile(__dirname + `/xx.txt`, 'utf8', function (err,data) {
            if (err) {
                // update error for usage in next MIDDLEWARE
                req.output = {
                    statusCode : 401,
                    message : `Bad - 401`
                }
                return next(err);
            }

        //DO SOMETHING WITH the data        

        fs.writeFile(__dirname + `/yy.txt`, "DATA", 'utf8', function (err) {            
            // update error for usage in next MIDDLEWARE
            if (err) {
                req.output = {
                    statusCode : 409,
                    message : `Bad - 409`
                }
                return next(err);
            }
        });
    }); //end of readFile()

    next();
}

var middle_2 = function  (req, res, next) {

    // SOME THINGS DONE HERE

    next();

}


var response_end = function(req, res) {

    //setup my Status and Message response
    var status = req.output.statusCode;
    var message = req.output.message;

    res.status(status).send(message);
}


app.post('/' ,middle_1, middle_2, response_end )

【问题讨论】:

  • 你不需要middle_1中的最后一个next();
  • 宾果游戏!知道了!现在它可以工作了:-)。由于此解决方案,现在出现了一个小的后果问题 - 我看到错误消息和状态(500 内部服务器错误)正在覆盖我的 res.status().json() 响应......我现在如何才能在response_end() 并相应地更新我的状态和消息,这样我就不会在我的服务器之外暴露内部错误?
  • 您应该阅读快速错误处理程序的工作原理

标签: node.js express error-handling middleware


【解决方案1】:

@blazesahlzen 解决方案对我有用。 再次感谢您的帮助:-)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2011-08-27
    • 2015-04-07
    • 2013-04-17
    • 1970-01-01
    相关资源
    最近更新 更多