Reputation: 1499
I am new to NodeJS. So I am writing NodeJS application with socket.io.
I understand how to separate controllers. In my app I created:
controllers/userCtrl.js
controller/marketCtrl.js
etc.
And in userCtrl.js
controller I did like this:
exports.create = function(req, res) {
// Create user
}
// Other actions
In application I use it:
// ...
var userCtrl = require('./controllers/userCtrl');
app.post('/user', userCtrl.create);
// ...
With models the same. But I have a lot of socket.io related code in app.js
and don't understand how remove it (like controllers) from app.js
:
var frontend = io.of('/frontend');
frontend.on('connection', function (client) {
logger.info('Someone connected to frontend socket');
client.on('join', function (message) {
logger.info('In join event');
var token = message.token;
if (!token) {
logger.debug('No usertoken provided. Sending login required');
client.emit('join', {error: 103, message: 'Login required', data: null});
return;
}
//... etc..
My question is: How to split socket.io related code into files? What is best practice for it? Thank you!
Upvotes: 2
Views: 1837
Reputation: 6017
Different files is still the way. Use exports
or module.exports
and then just require
in your app.js
.
Perhaps make a setup()
function that takes in an app/http instance, or whatever else you need in your socket.io stuff, and then call that function at the right time in app.js.
-- socketSetup.js --
'use strict';
var io = require('socket.io');
function setup( app, logger, whatever ){
//do stuff here
}
module.exports = setup;
-- app.js --
'use strict';
var express = require('express');
var socketSetup = require('./socketSetup.js');
var app = express();
//other express things
//setup the socket stuff
socketSetup( app, logger );
The result is a shorter and more readable app.js
file, and your socket setup is contained as well. Repeat as things grow in your socketSetup.js
file as well.
Upvotes: 1