javascript – 来自http请求的Node.js响应不会调用’end’事件而不包括’data’事件

所以我有一个简单的客户端应用程序与node.js中的服务器端应用程序通信.在客户端,我有以下代码:

function send (name) {
    http.request({
        host: '127.0.0.1',
        port: 3000,
        url: '/',
        method: 'POST'
    }, function (response) {
        response.setEncoding('utf8');
        response.on('data', function (data) {
           console.log('did get data: ' + data);
        });
        response.on('end', function () {
            console.log('\n   \033[90m request complete!\033[39m');
            process.stdout.write('\n your name: ');
        });
        response.on('error', function (error) {
            console.log('\n Error received: ' + error);
        });
    }).end(query.stringify({ name: name})); //This posts the data to the request
}

奇怪的是,如果我不通过以下方式包含“数据”事件:

    response.on('data', function (data) {
       console.log('did get data: ' + data);
    });

响应的“结束”事件永远不会被关闭.

服务器代码如下:

var query = require('querystring');
require('http').createServer(function (request, response) {
    var body = '';
    request.on('data', function (data) {
       body += data;
    });
    request.on('end', function () {
        response.writeHead(200);
        response.end('Done');
        console.log('\n got name \033[90m' + query.parse(body).name + '\033[39m\n');
    });
}).listen(3000);

我想知道为什么当文档(据我所知)不需要您收听数据事件以关闭响应会话时会发生这种情况.

只有当所有数据都被使用时,才会调用’end’,请查看下面的引用:

Event: ‘end’

This event fires when no more data will be provided.

Note that the end event will not fire unless the data is completely
consumed. This can be done by switching into flowing mode, or by
calling read() repeatedly until you get to the end.

但是为什么你需要调用.on(‘data’,..)?答案是

If you attach a data event listener, then it will switch the stream
into flowing mode, and data will be passed to your handler as soon as
it is available.

所以基本上通过添加数据监听器,它将流改变为流模式并开始消耗数据.

请查看this link以获得更多的参考.

翻译自:http://stackoverflow.com/questions/23817180/node-js-response-from-http-request-not-calling-end-event-without-including-da

转载注明原文:javascript – 来自http请求的Node.js响应不会调用’end’事件而不包括’data’事件