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
Listening on

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

Love podcasts or audiobooks? Learn on the go with our new app.