0

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});
}
killstreet
  • 1,251
  • 2
  • 15
  • 37
  • Are you looking for [module.exports](http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) ? – sknt May 22 '17 at 08:15
  • @Skynet This will result in what I already have by calling rooms.join inside an event. But more, I'd like to completely be able to move the entire event call to a different file. For example, roomEvents.js will catch all events that have something to do with rooms, messagesEvents.js will catch all events that are linked to messages. – killstreet May 22 '17 at 08:26
  • I've updated the question better explaining the result I was wondering if that was possible with nodejs. Not so much for creating aliases as the post you've linked to is doing. – killstreet May 22 '17 at 08:42

0 Answers0