Skip to content

JsCommunity/http-server-plus

Repository files navigation

http-server-plus

Package Version Build Status PackagePhobia Latest Commit

Drop-in replacement for http.Server that can listen on multiple ports/sockets and mix HTTP, HTTPS and HTTP/2 on a single instance

http-server-plus is meant to be used exactly like Node's native http.Server (or https.Server): same events, same general shape. The only reason it exists is that a native server can only ever listen on a single port/socket with a single protocol, whereas this one can listen on as many of them as you want — HTTP, HTTPS and HTTP/2 included — and still behave as a single logical server. See Divergences from http.Server below for the handful of places where that necessarily changes the API.

Install

Installation of the npm package:

npm install --save http-server-plus

Example

// The `create()` method can also take a `requestListener`, just like
// `http.createServer()`.
var app = require("express")();
var server = require("http-server-plus").create(app);

// The listen method returns a promise which resolves when the server
// starts listening.
Promise.all([
  // Listen on port localhost:80.
  server.listen({
    hostname: "localhost",
  }),

  // Listen on port 443, using HTTPS.
  server.listen({
    cert: require("fs").readFileSync(__dirname + "/certificate.pem"),
    key: require("fs").readFileSync(__dirname + "/private_key.pem"),
  }),

  server.listen({
    // Listen on localhost:8080
    port: 8080,
  }),

  // Listen on socket.
  server.listen({
    socket: __dirname + "/http.sock",
  }),

  // Listen on file descriptor (with systemd for instance).
  server.listen({
    fd: 3,
  }),

  // Listen on a socket created by systemd.
  server.listen({
    systemdSocket: 0, // this is a socket index
  }),
])
  .then(function (niceAddresses) {
    console.log("server is listening on", niceAddresses);
  })
  .catch(function (error) {
    console.error("The server could not listen on", error.niceAddress);
  });

As a convenience, if hostname is localhost, it will listen on both IPv4 (127.0.0.1) and IPv6 (::1), similar to what Node does if no hostname are provided (0.0.0.0 and ::).

Using ES2016's async functions:

import createExpressApp from "express";
import { create } from "http-server-plus";

async function main() {
  const app = createExpressApp();

  // The `create()` method can also take a `requestListener`, just
  // like `http.createServer()`.
  const server = create(app);

  try {
    // The listen method returns a promise which resolves when the server
    // starts listening.
    const niceAddresses = await Promise.all([
      // Listen on port localhost:80.
      server.listen({
        hostname: "localhost",
        port: 80,
      }),

      // Listen on port 443, using HTTPS.
      server.listen({
        port: 443,

        cert: require("fs").readFileSync(__dirname + "/certificate.pem"),
        key: require("fs").readFileSync(__dirname + "/private_key.pem"),
      }),

      // Listen on socket.
      server.listen({
        socket: __dirname + "/http.sock",
      }),
    ]);

    console.log("the server is listening on", niceAddresses);
  } catch (error) {
    console.error("the server could not listen on", error.niceAddress);
  }
}

Using HTTP/2:

var server = require("http-server-plus").create(
  {
    createSecureServer: require("http2").createSecureServer,
  },
  app,
);

API

create([opts], [requestListener])

Creates a new server instance. requestListener is registered as a request listener, just like http.createServer(requestListener). opts.createServer/opts.createSecureServer let you swap in alternative implementations (e.g. http2 or spdy, see above).

.listen(opts)

Starts listening according to opts (hostname/port, socket, fd, systemdSocket, or cert/key/pfx/SNICallback for HTTPS — see the examples above). Can be called multiple times on the same instance to listen on several ports/protocols at once.

Returns a promise resolving with a human-readable address (e.g. "http://127.0.0.1:8080") once actually listening, or rejecting with the underlying error (with an extra .niceAddress property) if it fails to start.

.addresses()

Returns the list of addresses (as returned by Node's server.address()) the instance is currently listening on — one entry per .listen() call that succeeded so far.

.close([callback])

Closes every underlying server. Returns a promise that resolves once the close event has fired (see below), in addition to accepting an optional Node-style callback.

.ref() / .unref()

Calls .ref()/.unref() on every underlying server, same semantics as the native methods.

Events

checkContinue, checkExpectation, clientError, connect, connection, listening, request and upgrade are forwarded from every underlying server to the instance, so you can listen for them exactly as you would on a plain http.Server.

close is emitted once all underlying servers have closed (or immediately, asynchronously, if there were none to begin with).

error is emitted for errors that happen on a server after it has started listening — mirroring how a native http.Server behaves once listening, including the fact that Node will throw if nothing is listening for it. Errors happening while a server is still trying to start listening are not emitted this way, see below.

Divergences from http.Server

  • .addresses() instead of .address(): since a single instance can be listening on several ports/sockets, there isn't a single address to return.
  • .listen() returns a promise instead of being fire-and-forget with a listening/error event to react to. This also means it can be called multiple times, once per port/socket/protocol you want to listen on.
  • Errors during the initial .listen() attempt reject its promise instead of being emitted as an error event. They are only ever surfaced that way, to avoid signaling the same failure twice. Once a server has successfully started listening, subsequent errors are forwarded as error events, same as a native server.
  • .close() returns a promise in addition to accepting an optional callback.

Contributions

Contributions are very welcomed, either on the documentation or on the code.

You may:

  • report any issue you've encountered;
  • fork and create a pull request.

License

ISC © Julien Fontanet

About

Augmented http.Server, HTTP/HTTPS and multiple ports on the same instance

Resources

License

Stars

4 stars

Watchers

1 watching

Forks

Packages

 
 
 

Contributors