2

I'm working on my first node project, I basically followed the thinkster post to get me started. I've managed to build a simple app and now I'm trying to configure socket.io.

The socket.io initialization code and event handlers are not hard to understand, what is really confusing me is how should I organize that code between the bin/www and the app.js files. Both files were generated automatically by express. bin/www depends on the app.js module, the first initiates the server variable which is needed to start up the socket module, so that means I should put all the 'socket.io' code in the bin/www file?

I don't think I should be touching that file though, I would be more comfortable putting that code into app.js or even inside a dedicated file. I think I need to pass the server object reference between modules, but I'm not sure how to do that.

This is the content of the bin/www file:

#!/usr/bin/env node /** * Module dependencies. */ var app = require('../app'); var debug = require('debug')('oculus:server'); var http = require('http'); /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '3000'); 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); } 

And this the content of the app.js file:

var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); // Mongoose require('./models/Aplicacoes'); mongoose.connect('mongodb://localhost/oculus'); var routes = require('./routes/index'); var users = require('./routes/users'); 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(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); // 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 handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); /** * Some business code here */ .... module.exports = app; 

this is my project structure

2 Answers 2

3

First, let me tell you, what you're trying to do is kinda right. Not to mess with the bin/www would be fine.

But remember express generator is just that. A generator for you to build upon. You generate, and the apply your own modifications.

My choice would be to:

  • copy bin/www to a new bin/wwwio,
  • Update the bin/wwwio script to attach socket.io to the created http server.
  • Update bin/wwwio to require() a new file ../io.js that handles all my socket.io events.
  • Modifiy package.json to run node ./bin/wwwio on npm start instead of bin/www

You can also look at the answers on this other question about the some topic:

Using socket.io in Express 4 and express-generator's /bin/www

You'll find several approaches to achieving modularity with little touching on the bin/www script.

Sign up to request clarification or add additional context in comments.

Comments

0

Try following these simple steps

Install Socket.io with the following command:

npm install --save socket.io

Add the following to app.js:

var sockIO = require('socket.io')(); app.sockIO = sockIO; 

In bin/www,

after var server = http.createServer(app), add the following: var sockIO = app.sockIO; sockIO.listen(server); 

To test functionality, in app.js, you can add the line:

sockIO.on('connection', function(socket){ console.log('A client connection occurred!'); }); 

Now in layout.hbs add the following snippet before the body closing tag < /body >:

<script src="/socket.io/socket.io.js"></script> <script> var socket = io(); </script> 

Further, I have created the GIT REPOSITORY for the complete working project of chat with Sockets express generator.

https://github.com/Mohsin05/Sockets-Express-Generator

I hope it will help everyone. ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.