Separate Socket.io into app.js

1.8k views Asked by At

I'm working on my Express project right, currently I have app.js, socket folder where are my sockets , but all my logic is in bin/www since Im using sockets in my routes like this:

 req.io.emit('dataUpdated', { id: client });

but I would like to seperate it into app.js how could I do that without breaking my app.

here is my www file:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('../config.json');
var appRoutes = require('./routes/Approutes');


var app = express();

app.use(express.static(path.join(__dirname, '../public')));

mongoose.Promise = global.Promise;
mongoose.connect('localhost/db_test');

app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'hjs');

app.set('appProperties', {
  secret: config.secret
});

var siofu = require("socketio-file-upload");
app.use(siofu.router);


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


var debug = require('debug')('express-seed:server');
var server = require('http').Server(app);

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Set socket
 */

var socketioJwt = require('socketio-jwt');
var socketIo = require('socket.io');
var io = socketIo.listen(server);


io.use(socketioJwt.authorize({
   secret: config.secret,
   handshake: true
}));

app.io = io;
app.use(function(req, res, next) { 'use strict'; req.io = io; next(); });


app.use('/', appRoutes);



require('../sockets/user')(io);


/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

my app.js file is empty... and my socket file

exports = module.exports = function (io) {
 io.sockets.on('connection', (socket) => {
   socket.on('clientGetList', (req) => {
// getting clientList
});
})
}

How can I move my logic from www file to app.js file without breaking the app?

1

There are 1 answers

0
jfriend00 On BEST ANSWER

I would like to move my middleware, and socket connection to app.js and in www just to start server

You can separate the code like this and pass both app and server variables to your app.js module where it can run the rest of the initialization code (middleware, routes, socket.io setup, etc...):

// www
const express = require('express');
const app = express();

const server = require('http').Server(app);

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

// load app.js and let it do it's part of the initialization of app and server
require('./app.js')(app, server);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

And, then this would be an outline for app.js:

const bodyParser = require('body-parser');
const siofu = require("socketio-file-upload");
const config = require('../config.json');
const appRoutes = require('./routes/Approutes');
const socketioJwt = require('socketio-jwt');
const socketIo = require('socket.io');

// export one function that gets called once as the server is being initialized
module.exports = function(app, server) {
    app.set('views', path.join(__dirname, '../views'));
    app.set('view engine', 'hjs');

    app.set('appProperties', {
      secret: config.secret
    });

    app.use(siofu.router);


    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));    

    var io = socketIo.listen(server);


    io.use(socketioJwt.authorize({
       secret: config.secret,
       handshake: true
    }));

    app.io = io;
    app.use(function(req, res, next) { 'use strict'; req.io = io; next(); });


    app.use('/', appRoutes);

    require('../sockets/user')(io);

}