NODEJS readFile,writeFile和中间件用于错误情况

时间:2017-02-23 13:14:02

标签: node.js express error-handling middleware

  1. 我想阅读文件xx.txt
  2. 操纵数据并写入文件yy.txt
  3. 所有这一切都在POST()中使用需要更新错误的中间件,并因此转移到下一级别,以便我可以正确回复状态和消息。
  4. 我一直看到 - 如果我使用异步模式进行读/写,我的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 )
    

1 个答案:

答案 0 :(得分:0)

@blazesahlzen解决方案为我工作。 再次感谢您的帮助: - )。