Zak Zak - 7 months ago 59
Javascript Question

Does node.js `response.end` event ever send the optional `data` and `encoding` parameters?

The documentation defines

response.end([data][, encoding][, callback])
, and states:


If data is specified, it is equivalent to calling response.write(data,
encoding) followed by response.end(callback).


Am I using the
end
event correctly, or is it highly unlikely anyone would pass data into the
end
event?

var http = require('http');

http.get(
process.argv[2],
function (response) {
response.setEncoding('utf8');
response.on('error', console.error);
response.on('data', console.log);

// Check for data and exit on 'end' event
response.on(
'end',
function (data, encoding) {
if ( null != data ) {
console.log(data.toString(encoding));
}
return;
}
);
}
);

Answer

response.on('end'...) indicated that there is no more data in the response.

The data is sent in chunks as mentioned in the docs. It is a readable stream, on('end') allows you to pass in your own data, you could have simple text in there and that is what would be written like so:

The docs are essentially explaining the two ways you can do this.

Example:

response.write('Hello World\n');
response.end();

OR
response.end('Hello World\n');

Generally speaking this is fine for small amounts of data, but chunking of the data is handled in response.on('data'...); which is where you can put the data into lets say, an Array, and then pass that Array in to response.on('end'...) which is how I would recommend doing it for larger chunked data. A good exercise might be to log the data in a callback to see it come through.

Edit:

To your question in the comments:

Your code is correct, and optional, think about it this way, you send something to that function, a request, it does a response, that response if its large is broken into chunks, you can get those chunks in on(data), you can send it back at the end using on(end), simple as that

Hope that helps.