/* * Copyright (C) 2019 StApps * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ import {Logger} from '@openstapps/logger'; import * as http from 'http'; import {app} from './app'; /** * Get port from environment and store in Express. */ // tslint:disable-next-line: strict-boolean-expressions const port = normalizePort(process.env.PORT || '3000'); // TODO: Can we remove that? It doesn't look like it is read at all. app.set('port', port); /** * Create HTTP server. */ const server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(value: string) { const portNumber = parseInt(value, 10); if (isNaN(portNumber)) { // named pipe return value; } if (portNumber >= 0) { // port number return portNumber; } return false; } /** * Event listener for HTTP server "error" event. */ // tslint:disable-next-line: completed-docs async function onError(error: { code: string; syscall: string; }) { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': await Logger.error(`${bind} requires elevated privileges`); process.exit(1); break; case 'EADDRINUSE': await Logger.error(`${bind} is already in use`); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { const addr = server.address(); const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`; Logger.ok(`Listening on ${bind}`); }