node.js - include .js files within socket.on('connection') method

Problem

Is it possible to include files like this? I need write a lot of code and it could help me with clarity. P.S. Sorry for my English ;)

io.sockets.on('connection', function(client) {
// include file1.js
// include file2.js
});

Content of file1.js

client.on('event1',function() {
// do something here...
});

Content of file2.js

client.on('event2',function() {
// do something here...
});
Problem courtesy of: Quak

Solution

If you don't need to conditionally load the JavaScript files, you could do something like this:

main.js

io.sockets.on('connection', function(client) {
  setup1(client);
  setup2(client);
});

file1.js

function setup1(client) {
  client.on('event1',function() {
  // do something here...
  });
}

file2.js

function setup2(client) {
  client.on('event2',function() {
  // do something here...
  });
}

And of course you could make it all cleaner by using a library like Postal.js to handle inter-application communication.

Solution courtesy of: Jacob Gillespie

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.