Koa listening on HTTP and HTTPS and reporting port and ip

This little snippet creates a Koa server that listens on both HTTP and HTTPS ports and prints the exact address it is listenning to.

const http = require('http');const https = require('https');const Koa = require('koa');
const app = new Koa();
// Settings
const HOST = 'localhost';
const HTTP_PORT = 3000;
const HTTPS_PORT = 3001;
app.use(async ctx => {
ctx.body = 'Hello World';
});
// Listen
const httpServer = http.createServer(app.callback())
.listen(HTTP_PORT, HOST, listeningReporter)
const httpsServer = https.createServer(app.callback())
.listen(HTTPS_PORT, HOST, listeningReporter)
// A function that runs in the context of the http server
// and reports what type of server listens on which port
function listeningReporter () {
// `this` refers to the http server here
const { address, port } = this.address();
const protocol = this.addContext ? 'https' : 'http';
console.log(`Listening on ${protocol}://${address}:${port}...`);
}

It prints:

Listening on http://127.0.0.1:3000...
Listening on https://127.0.0.1:3001...

Written by

Knowledge Worker, MSc Systems Engineering, Tech Lead, Web Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store