@@ -15,26 +15,56 @@ const certOptions = {
1515
1616// run express on 443
1717const app = express ( )
18- https . createServer ( certOptions , app ) . listen ( 443 )
18+ app . server = https . createServer ( certOptions , app ) . listen ( 443 )
19+ // save sockets for fast close
20+ const sockets = [ ]
21+ let nextSocketId = 0
22+ app . server . on ( 'connection' , socket => {
23+ const socketId = nextSocketId ++
24+ sockets [ socketId ] = socket
25+ socket . on ( 'close' , ( ) => delete sockets [ socketId ] )
26+ } )
1927
2028// gzip compression and minify
2129app . use ( compression ( ) )
2230app . set ( 'json spaces' , 0 )
2331
2432// redirect http to https
25- http . createServer ( function ( req , res ) {
33+ app . http = http . createServer ( function ( req , res ) {
2634 res . writeHead ( 301 , { "Location" : "https://" + req . headers [ 'host' ] + req . url } )
2735 res . end ( )
2836} ) . 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+ } )
2943
3044// ready
31- console . info ( "Server running on port 443." )
45+ if ( ! process . env . TEST ) console . info ( "Server running on port 443." )
3246
3347// serve static files, launch as: 'node index.js <static-path>'
3448if ( require . main === module ) { // called directly (not through require)
3549 const staticPath = process . argv [ 2 ]
3650 app . use ( express . static ( staticPath || process . cwd ( ) ) )
3751}
3852
53+ // close the app
54+ app . close = ( callback ) => {
55+ const promises = [
56+ new Promise ( resolve => app . http . close ( resolve ) ) ,
57+ new Promise ( resolve => app . server . close ( resolve ) )
58+ ]
59+ // destroy all opens
60+ for ( const socketId in sockets )
61+ sockets [ socketId ] . destroy ( )
62+
63+ return Promise . all ( promises ) . then ( ( ) => {
64+ if ( ! process . env . TEST ) console . info ( "Server closed." )
65+ if ( callback ) callback ( )
66+ } )
67+ }
68+
3969// export as module
4070module . exports = app
0 commit comments