@@ -7,15 +7,21 @@ const https = require('spdy') // using HTTP/2: spdy will be deprecated soon, wai
77const express = require ( 'express' )
88const compression = require ( 'compression' )
99
10- // SSL certificate
10+ // SSL CERTIFICATE
1111const certOptions = {
1212 key : fs . readFileSync ( path . resolve ( __dirname + "/cert/server.key" ) ) ,
1313 cert : fs . readFileSync ( path . resolve ( __dirname + "/cert/server.crt" ) )
1414}
1515
16- // run express on 443
16+ const port = process . env . PORT || 443
17+
18+
19+ // START THE APP
20+
21+ // run express
1722const app = express ( )
18- app . server = https . createServer ( certOptions , app ) . listen ( 443 )
23+ app . server = https . createServer ( certOptions , app ) . listen ( port )
24+
1925// save sockets for fast close
2026const sockets = [ ]
2127let nextSocketId = 0
@@ -30,27 +36,30 @@ app.use(compression())
3036app . set ( 'json spaces' , 0 )
3137
3238// redirect http to https
33- app . http = http . createServer ( function ( req , res ) {
34- res . writeHead ( 301 , { "Location" : "https://" + req . headers [ 'host' ] + req . url } )
35- res . end ( )
36- } ) . listen ( 80 )
37- // save sockets for fast close
38- app . server . on ( 'connection' , socket => {
39- const socketId = nextSocketId ++
40- sockets [ socketId ] = socket
41- socket . on ( 'close' , ( ) => delete sockets [ socketId ] )
42- } )
39+ if ( port === 443 || process . env . HTTP_PORT ) {
40+ app . http = http . createServer ( function ( req , res ) {
41+ res . writeHead ( 301 , { "Location" : "https://" + req . headers [ 'host' ] + req . url } )
42+ res . end ( )
43+ } ) . listen ( process . env . HTTP_PORT || 80 )
4344
44- // ready
45- if ( ! process . env . TEST ) console . info ( "Server running on port 443." )
45+ app . http . on ( 'connection' , socket => {
46+ const socketId = nextSocketId ++
47+ sockets [ socketId ] = socket
48+ socket . on ( 'close' , ( ) => delete sockets [ socketId ] )
49+ } )
50+ }
4651
47- // serve static files, launch as: 'node index.js <static-path>'
52+ // SERVE STATIC FILES, if launched as: 'node index.js <static-path>'
4853if ( require . main === module ) { // called directly (not through require)
4954 const staticPath = process . argv [ 2 ]
5055 app . use ( express . static ( staticPath || process . cwd ( ) ) )
5156}
5257
53- // close the app
58+ // ready
59+ if ( ! process . env . TEST ) console . info ( "Server running on port " + port + "." )
60+
61+
62+ // CLOSE THE APP
5463app . close = ( callback ) => {
5564 const promises = [
5665 new Promise ( resolve => app . http . close ( resolve ) ) ,
0 commit comments