检查流是否包含数据

时间:2014-02-18 18:09:19

标签: javascript node.js

考虑以下代码......

http.createServer(function(req, res){

    // Emit an event where res MIGHT be modified
    // res may have its write() method called
    // it also may have its end() method called
    self.emit('somethingHappened', res);

    // How do I know if res has been ended?
    if(res.hasEnded){
        // Response was written and sent, nothing to do
        return;
    }

    // How do I know if res data has been set?
    if(!res.hasData){
        // Write some data
    }

    res.end();
});
  • 如何检查res是否已结束?
  • 如何检查res是否包含任何数据?

1 个答案:

答案 0 :(得分:0)

您可以在res中查看res.finished是否已结束。如果我们想知道是否已发送某些数据,我个人会使用res.socket._bytesDispatched获取该信息。你可以在这里看到它是如何工作的:

    http.createServer(function(req, res){

        console.log('Have we sent data?',res.socket._bytesDispatched>0);
        res.write('HELLO');
        console.log('Have we sent data?',res.socket._bytesDispatched>0);

        console.log('Have we finished?',res.finished);
        res.end();
        console.log('Have we finished?',res.finished);

    }).listen(3000);