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 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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' ?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.