Zak Zak - 1 year ago 115
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
event correctly, or is it highly unlikely anyone would pass data into the

var http = require('http');

function (response) {
response.on('error', console.error);
response.on('data', console.log);

// Check for data and exit on 'end' event
function (data, encoding) {
if ( null != data ) {


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.


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

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.


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.