3

I've seen the following setup for a node express server:

server.js

import { Server } from 'http'; 
import Express from 'express'; 

const app = new Express(); 
const server = new Server(app);

Since it is possible just to run express directly, what is the advantage here of returning the express server as an argument of the http server?

1 Answer 1

7

Express is a request handler for an HTTP server. It needs an HTTP server in order to run. You can either create one yourself and then pass app as the request handler for that or Express can create it's own HTTP server:

import Express from 'express'; 
const app = new Express();
app.listen(80);

But, just so you fully understand what's going on here. If you use app.listen(), all it is doing is this (as shown from the Express code):

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

which is just creating its own vanilla http server and then calling .listen() on it.


If you are just using a plain vanilla http server, then it saves you some code to have Express create it for you so there's really no benefit to creating it for yourself. If, you want to create a server with some special options or configurations or if you want to create an HTTPS server, then you must create one yourself and then configure it with the Express request handler since Express only creates a plain vanilla http server if you ask it to create it yourself. So, create one yourself if you need to create it with special options.

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

7 Comments

The practice of creating a separate http.Server is very widespread (for example. the socket.io example code does it as well). I guess that a lot of people see that and think that that's how it should be done.
@robertklep - There's nothing wrong with creating your own http server manually. Express just offers a shortcut that will do it for you.
Thanks that helps. So in that case, it's redundant to explicitly create an http-server?
I didn't mean to imply that it's wrong, it's just extra code :) And I've seen it cause issues, by people calling app.listen() instead of server.listen(), and not realizing that they started a new HTTP server, instead of the one represented by server.
@Paulos3000 - It's not redundant. Somebody has to create one. You either create one yourself or you ask express to do it for you. But, it does save code to have Express do it for you. Note, if you are, for example, trying to instantiate and https version of your server, then Express can't do that for you so you'd have to create your own http server manually.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.