On the socket.io web page, Get Started: Chat application
, located here:
http://socket.io/get-started/chat/
there is this code:
var app = require('express')(); var http = require('http').Server(app);
which could be rewritten a little more clearly like this:
var express = require('express'); var http = require('http'); var app = express(); var server = http.Server(app);
The socket.io example uses http.Server() to create a server. Yet, the express docs for app.listen() show an example where the server is created using http.createServer(app)
:
app.listen()
Bind and listen for connections on the given host and port. This method is identical to node's http.Server#listen().var express = require('express'); var app = express(); app.listen(3000);
The app returned by express() is in fact a JavaScript Function, designed to be passed to node's HTTP servers as a callback to handle requests. This allows you to provide both HTTP and HTTPS versions of your app with the same codebase easily, as the app does not inherit from these (it is simply a callback):
var express = require('express'); var https = require('https'); var http = require('http'); var app = express(); http.createServer(app).listen(80); https.createServer(options, app).listen(443);
The app.listen() method is a convenience method for the following (if you wish to use HTTPS or provide both, use the technique above):
app.listen = function(){ var server = http.createServer(this); return server.listen.apply(server, arguments); };
What's the difference between http.createServer(app)
and http.Server(app)
?? The http docs are no help.
The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.
The usual two ways to start a server for use with Express are this: var express = require('express'); var app = express(); // Express creates a server for you and starts it var server = app. listen(80);
The Express philosophy is to provide small, robust tooling for HTTP servers, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs. Navigate to the port 3000 as previously set in the server.
There is no difference. http.createServer()
only does one thing: it calls http.Server()
internally and returns the resulting instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With