In node.js, a tcp server has the following methods to listen:
server.listen(port, [host], [backlog], [listeningListener])
server.listen(path, [listeningListener])
server.listen(handle, [listeningListener])
I would like to create an application specific server which calls this lower level tcp server. I would like to provide my users with a listen method which just calls the right listen method of a tcp server.
Is there a way for me to avoid writing three different listen methods, and passing their arguments to the three tcp server's listen methods? Will it pass on optional parameters?
Can I just do something like this (with slightly made up syntax):
myapp.listen(args*){
tcpserver.listen(args*);
}
In JavaScript, all of a function's arguments are always available under the name arguments
, whether or not they also have their own names; so you can write:
myapp.listen(){
tcpserver.listen.apply(tcpserver, arguments);
}
using the function Function.apply
to forward arguments
to the desired method-call.
Edited to add: I should also clarify that although this:
In node.js, a tcp server has the following methods to listen […] the three tcp server's listen methods […]
is consistent with the way the Node.js documentation describes things, it's not strictly accurate. JavaScript doesn't have any concept of function/method overloading; rather, it must be that a Server
object has a single listen
method that examines its first argument to determine which "overload" to execute.