0

How can I assign a call back function for event 'data' and give it more then 1 standard parameter ? Here is my script :

var http = require('http');
var server = http.createServer().listen(8080);

server.on('request', onRequest);
server.on('listening', onListening);

function onRequest(request, response)
{
    response.writeHead(200);
    request.on('data', function(){onReqData(data,res)});
    request.on('end', onReqEnd);
}

function onReqData(data, response)
{
    console.log('Request : ', data.toString());
    response.write('Write : ' + data.toString());
}

function listen()
{
    console.log('--- / Server runs on 8080 / --- ');
} 

function onReqEnd()
{
    console.log(' - - - / The end of request / - - - ');
}

I don't like the syntax where the body of the callback function is in the .on() block.
So when I'm trying to assign a callback like this : request.on('data', onReqData); without declaring function incoming params (function onReqData(){...} ) I have an error which tells me that response is undefined

request.on('data', function(){onReqData(data,res)});

Gives me an error that data is undefined.

Any help will be greatly appreciated !

1 Answers1

1

The 'data' event will call your function passing a chunk of data. You need to accept chunk as a function parameter and pass it on to your onReqData function.

Edit: You also need to pass the same response variable to onReqData.

function onRequest(request, response)
{
    response.writeHead(200);
    request.on('data', function(chunk){onReqData(chunk, response)});
    request.on('end', onReqEnd);
}
gregnr
  • 1,222
  • 8
  • 11
  • Gregnr, thank you for your answer, it helped. Can you give me a link or an advise how to google this question, 'cause now I'm confused more than before. What's the difference between 'data' and 'chunk' ? – slaventiy_k Mar 22 '15 at 20:37
  • The data event only passes a chunk (segment) of the data at a time. This is due to the nature of packets - if all the data can't fit in one packet, it gets split into multiple. The data event allows you to grab the data as it comes rather than waiting for the entire payload. You can call the variable whatever you like, but 'chunk' is a better description IMO. – gregnr Mar 22 '15 at 21:03
  • 1
    See https://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request And http://stackoverflow.com/questions/11237015/why-is-node-js-breaking-incoming-data-into-chunks – gregnr Mar 22 '15 at 21:04