I use this function to get input data of requests in my Node.js application:
function getData(callback){
req.data = '';
req.receivedDataSize = 0;
req.maxDataSize = 5000;
req.dataCorrupted = false;
req.on('data', function(chunk){
if(req.dataCorrupted === false && chunk.length < req.maxDataSize && req.receivedDataSize < req.maxDataSize){
req.data += chunk;
req.receivedDataChunk += chunk.length;
} else {
// throw 413 error.
req.dataCorrupted = true;
return;
});
req.on('end', function(){
if(req.dataCorrupted === false){
callback(null);
} else {
callback('input-data-corrupted');
}
return;
});
}
I want to know how these "return" statements in each event callback are used, when I throw "return", what will happen on the next "req.on('data') || req.on('end')"? Is there a way to stop the event listener to stop listening to that event, or is just calling "req.end();" a proper way to stop?
In your example return
doesn't do anything, but end the function and return a value. It doesn't stop the stream from calling back. You can remove those statements completely from your code example and it would work the same.
Calling req.end()
should terminate it if it's a stream, which means req.on('data')
won't be triggered anymore.
Here's the not super helpful API docs about stream:
http://nodejs.org/api/stream.html#stream_stream_end
This is also a helpful guide to streams in node: http://maxogden.com/node-streams