Given code like this from a node.js neophyte like me:
require('http').createServer(function( req, resp ) {
var pathname = require('url').parse( req.url ).pathname;
if( req.method === "POST" ) {
var postData = "";
req.addListener( "data", function( postDataChunk ) {
postData += postDataChunk;
});
req.addListener( "end", function() {
// do my thing with postData
// and end the response
});
}
}).listen(8888);
…every time there’s a POST request, the set of anonymous functions sent to the listeners are recreated.
This seems (almost) required since node doesn’t send a second accumulator argument to the "data" listener, or a final result argument to the "end" listener. As such, the anonymous functions need to reference the postData variable in order to build the result.
My preference is to have named functions for the listeners created outside the server request handler, like this:
function data_listener( postDataChunk ) {
this.some_unique_property.accumulator += postDataChunk;
}
function end_listener() {
// do my thing with postData
// and end the response
}
require('http').createServer(function( req, resp ) {
var pathname = require('url').parse( req.url ).pathname;
if( req.method === "POST" ) {
req.some_unique_property = {
response: resp,
pathname: pathname,
accumulator: "",
};
req.addListener( "data", data_listener );
req.addListener( "end", end_listener );
}
}).listen(8888);
Since this in the listener functions is the request object, I’ve borrowed the request object to accumulate the post data so that I can create my functions once and reuse them.
Is this an acceptable/safe approach?
I prefer the latter approach versus many anonymous functions, because it makes it easier to organize code. Should the code to handle data grow large, the former has the potential to be a giant function with anonymous functions inside, and much harder to maintain.
With the latter, I can easily break code out into separate modules to keep things organized. It also lets me document the individual handlers easily if I use something like JSDoc for documentation.
The only recommendation I can give with the latter is some comment indicating what
thisis meant to represent so someone else that reads the code over doesn’t have to spend too much time thinking on it.