Node.js - res.end and res.write can accept a callback function

When creating a basic HTTP server with Node.js, I noticed that the res.write and res.end methods of the 'http.ServerResponse' object can both accept a callback function like so:

require('http').createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});

    res.write('Hello ', function() { console.log('here 1'); });
    res.end(' World', function() { console.log('here 2'); });
}).listen(1337, '127.0.0.1');

'Hello World' is output in the browser, and 'here 1' and 'here 2' is output into the terminal.

However, these callback arguments aren't documented anywhere, for instance http://nodejs.org/api/http.html#http_response_end_data_encoding unless I'm missing something.

So is it OK to use and relly these callback functions? I have an interesting use case for them. Or are they some internal use thing and should be avoided?

This appears to be a 'feature'. It is actually meant to be the encoding to be used in the body but the way the net module works is the second argument is an optional callback. The stack is like this (about)

res.write(data, encoding)
res._send(data, encoding)
res._writeRaw(data, encoding)
res.socket.write(data, encoding, cb)

At that last point the number of arguments changes from 2 to 3. data and encoding to data, encoding, optional callback. So what is happening is your function (as the encoding argument) is being passed to socket.write where encoding can be optional.

This could be considered a bug as you cannot push all three arguments from the response write method. I'd advise using it with extreme care.