Héctor
Héctor

Reputation: 26054

Understanding non-blocking IO in Node

What is the difference between these codes?

***First*

var express = require('express');
var app = express();

app.post('/', function (req, res) {

    console.log('Procesando abastecimiento...');

    var rawData = '';

    req.on('data', function (chunk) {
        rawData += chunk;
    });

    req.on('end', function(){
        console.log('Data recibida: ' + rawData);
        res.end();
    });    
});

Second

var express = require('express');
var app = express();

app.post('/', function (req, res) {

    console.log('Procesando abastecimiento...');

    var rawData = '';

    req.on('data', function (chunk) {
        rawData += chunk;
    });

    req.on('end', function(){
        console.log('Data recibida: ' + rawData);    
    }); 

    res.end();   
});

If I close the connection (res.end()) inside 'end' event's callback, will the client wait until all data is read? I don't understand the difference, I just know that my code is faster using the second way. Can you explain me why?

Upvotes: 1

Views: 36

Answers (1)

Joanvo
Joanvo

Reputation: 5817

In the first example you set the res.end(); instruction to be executed on the request end callback (i.e. then the end event is raised).

In the second one you call res.end(); right away without awaiting the request to end.

You can think of it as if the instruction req.on('end', ...) is a function that sets up a handler for an event that will come in the future, but the code there is not executed until the event is received.

Upvotes: 1

Related Questions