Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - Node.js response from http request not calling 'end' event without including 'data' event

So I have a simple client application communicating with a server side application in node.js. On the client side, I have the following code:

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('
   33[90m request complete!33[39m');
            process.stdout.write('
 your name: ');
        });
        response.on('error', function (error) {
            console.log('
 Error received: ' + error);
        });
    }).end(query.stringify({ name: name})); //This posts the data to the request
}

The odd part is, if I don't include the 'data' event via:

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

The 'end' event for the response is never fired off.

The server code is as follows:

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('
 got name 33[90m' + query.parse(body).name + '33[39m
');
    });
}).listen(3000);

I would like to know why this is happening when the documentation (to my knowledge) doesn't require you to listen in on the data event in order to close a response session.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The 'end' is invoked only when all the data was consumed, check the reference below:

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.

But why you need to call the .on('data',..)? The answer is

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.

So basically by adding the data listener, it changes the stream into flowing mode and starts consuming the data.

Please check this link for more reference about it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...