0
votes

I've used express-generator to create my app skeleton and since my file that creates the server and my routes are separated, I don't know where to setup the socket.io code. The tutorials usually have the server code, the socket.io code and the routes in 1 file.

app.js contains:

var routes = require('./routes/');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
                  secret: 'secretText',
                  saveUninitialized: true,
                  resave: true
                }))
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes.home);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

www contains:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

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

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

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

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

home.js

var express = require('express');
var router = express.Router();
var db = require('../helpers/db');

router.get('/', function(req, res, next) {
    res.send("Hello");
});

module.exports = router;

index.js

var home = require('./home');

module.exports = {
    home
};
1

1 Answers

1
votes

As with all module design and layout in node.js, there is no "right" answer. It depends upon your own design ideas, how much code you're going to have of different types, what code needs to share with what and so on. As such, I can offer some ideas and you can pick which seems to appeal to you.

  1. If your server-side socket.io code is fairly minimal, you can just include it in www where the server is initialized (since you need access to the server object there).

  2. If you want your server-side socket.io code in its own module, then you can put it in its own module/file and import that file into your www file much the same way you import app.js and then hook the app object up to your server. Similarly, you would create the socket.io instance in your socket.io module and then import that instance into www and hook that up to your server.

  3. If you have a lot of code sharing between your socket.io code and your app.js code or need to make socket.io calls from your app.js routes, then you may want to import the socket.io code into your app.js code and then export both app and socket.io instance from app.js so www can then hook them both up.