Skip to content

Commit

Permalink
support https server
Browse files Browse the repository at this point in the history
  • Loading branch information
ovnrain committed Aug 29, 2023
1 parent eb2be59 commit 3ba91bd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
declare namespace NodeJS {
interface ProcessEnv {
PORT?: string;
SSL_CERT?: string;
SSL_KEY?: string;
}
}
25 changes: 22 additions & 3 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,37 @@
import http from 'http';
import fs from 'fs';
import http, { Server } from 'http';
import https from 'https';
import { normalizePort } from './utils.js';
import app from './app.js';
import type { ListenError } from './types.js';

const PORT = normalizePort(process.env.PORT || '3000');
const SSL_CERT = process.env.SSL_CERT;
const SSL_KEY = process.env.SSL_KEY;

const server = http.createServer(app);
let server: Server;
let scheme: 'http' | 'https';

if (SSL_CERT && SSL_KEY && fs.existsSync(SSL_CERT) && fs.existsSync(SSL_KEY)) {
server = https.createServer(
{
cert: fs.readFileSync(SSL_CERT),
key: fs.readFileSync(SSL_KEY),
},
app,
);
scheme = 'https';
} else {
server = http.createServer(app);
scheme = 'http';
}

server.listen(PORT);
server.on('error', onError);
server.on('listening', onListening);

function onListening() {
console.log(`Server is running at http://localhost:${PORT}`);
console.log(`Server is running at ${scheme}://localhost:${PORT}`);
}

function onError(error: ListenError) {
Expand Down

0 comments on commit 3ba91bd

Please sign in to comment.