I was wondering if it was possible to use multiple files on nodeJS that will catch events and handle them?
For example right now I have a server.js which is filled with code to handle chats and chatrooms.
Which would briefly just look as follow
var fs = require( 'fs' );
var app = require('express')();
var https = require('https');
server.listen(1234);
io.on('connection', function(client){
client.on('room_join', function(roomId){(
client.join(roomId);
});
client.on('message', function(data){
io.to(data.roomId).emit('message', {message: data.message});
});
});
Now what I would prefer if possible, is to create a messages.js, and rooms.js file that will handle this. But I would actually prefer those catching the events aswell. So my rooms.js file would look something like this
//rooms.js
client.on('room_join', function(roomId){( //Catching the event
client.join(roomId); //Still able to handle the client property made in the sever.js
});
Is such thing possible, or can I only require the rooms.js file and use it as follow
var rooms = require('modules/rooms.js');
client.on('room_join', function(roomId){
rooms.join(roomId);
});
A prefered solution would be something with the following structure
//server.js
var fs = require( 'fs' );
var app = require('express')();
var https = require('https');
var messagesEvents = require('events/messages.js');
var roomEvents = require('events/rooms.js');
server.listen(1234);
// events/messages.js
var messages = require('../modules/messages.js');
io.on('connection', function(client){
client.on('message', function(data){
messages.send(client, data, io);
});
});
// modules/messages.js
function send(client, data, io){
return io.to(data.roomId).emit('message', {message: data.message});
}