1

I have just started using node.js and I can build a simple app that responds to requests and has some basic routing using the express framework.

I am looking to create something using socket.io but I am slightly confused over the use of the 'http' module. I understand what http is but I don't seem to need it for the following to work:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.htm');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

I can serve a html page over http without requiring the http module explicitly with something such as:

var http = require('http');

If I am using express do I have any use for the http module?

Samuel Barnes
  • 113
  • 10

2 Answers2

9
var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();
var socketio  = require('socket.io');

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

source

http://stackoverflow.com/questions/17696801/express-js-app-listen-vs-server-listen
Pranav Bhatt
  • 715
  • 4
  • 8
1

no, you probably don't need it. You can use something like:

var app = require('express').createServer();
var io = require('socket.io')(app);

//Your express and socket.io code goes here:

KAKAN
  • 29
  • 5