Monday, 22 May 2017

Nodejs using multiple files to catch events

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);
});



via killstreet

No comments:

Post a Comment