First of all I know a similar question has been asked here, however, I did not understand the answer and my question is worded slightly differently so I am wondering if I can get a more clear answer.
The Express Generator starts an app like so:
app.js
var express = require('express');
var routes = require('./routes/index');
var users = require('./routes/users');
var io = require('socket.io');
(etc.)
I want to use Socket.io so I also install it and require it and following the Socket Docs do this
var server = express.createServer();
var io = require('socket.io')(server);
However, all of my routes, where I really want to handle socket.io events, take place on my routes/index.js page
. How do I use socket.io with my router, which is on a different page? How do I pass it in when my server instance was started on app.js (a different page)?
Furthermore, the socket.io docs list two ways to get started with express. The first example shows:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
And the second one shows:
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Can anyone explain the difference between using the "Express Framework" and "With Express 3 /4" as the documentation differentiates. I would also love to know why the examples use express.createServer()
(when a generated express app does not) and why the other example uses both the express
and http
node modules. Thank you