Paulos3000 Paulos3000 - 3 months ago 33
Node.js Question

Using both http-server and node express server

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


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?


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();

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.