@@ -4,42 +4,48 @@ const shutdownServer = require("http-graceful-shutdown");
44
55// this file will be glued to the top of the specific xy-serve.js file
66
7- function streamServerOutput ( instanceId , port ) {
8- debugLog ( `Server running on port ${ port } for instance ${ instanceId } ` ) ;
9- fs . writeFile ( "server.port.tmp" , port , err => {
10- if ( err ) return console . log ( err ) ;
11- fs . rename ( "server.port.tmp" , `server-${ instanceId } .port` , err => {
12- if ( err ) console . log ( err ) ;
13- } ) ;
7+ function getInstanceId ( ) {
8+ return process . argv . slice ( 2 ) . find ( arg => arg . startsWith ( "--node-server-instance-id=" ) ) ?. split ( "=" ) [ 1 ]
9+ || ( ( ) => { throw new Error ( "Missing --node-server-instance-id argument" ) ; } ) ( ) ;
10+ }
11+
12+ function streamOutput ( port , instanceId ) {
13+ debugLog ( "Server running on port " + port + " for instance " + instanceId ) ;
14+ fs . writeFile ( "server.port.tmp" , "" + port , function ( err ) {
15+ if ( err ) {
16+ return console . log ( err ) ;
17+ } else {
18+ fs . rename ( "server.port.tmp" , `server-${ instanceId } .port` , function ( err ) {
19+ if ( err ) {
20+ return console . log ( err ) ;
21+ }
22+ } ) ;
23+ }
1424 } ) ;
1525}
1626
1727function debugLog ( ) {
18- if ( false ) console . log . apply ( this , arguments ) ;
28+ if ( false ) { // set to true for debug log output in node process
29+ console . log . apply ( this , arguments ) ;
30+ }
1931}
2032
2133const app = express ( ) ;
2234
2335app . use ( express . json ( { limit : "50mb" } ) ) ;
2436
25- const server = app . listen ( 0 , "127.0.0.1" , ( ) =>
26- streamServerOutput (
27- process . argv . slice ( 2 ) . find ( arg => arg . startsWith ( "--node-server-instance-id=" ) ) ?. split ( "=" ) [ 1 ]
28- || ( ( ) => { throw new Error ( "Missing --node-server-instance-id argument" ) ; } ) ( ) ,
29- server . address ( ) . port
30- )
31- ) ;
37+ const server = app . listen ( 0 , "127.0.0.1" , ( ) => streamOutput ( server . address ( ) . port , getInstanceId ( ) ) ) ;
3238
3339app . post ( "/shutdown" , ( req , res ) => {
3440 setTimeout ( async ( ) => {
3541 try {
3642 await shutdownServer ( server , {
37- forceExit : false ,
38- finally : ( ) => debugLog ( "graceful shutdown finished." )
43+ forceExit : false , // let the event loop clear
44+ finally : ( ) => debugLog ( "graceful shutdown finished." ) ,
3945 } ) ( ) ;
4046 } catch ( err ) {
4147 console . error ( "Error during shutdown:" , err ) ;
4248 }
4349 } , 200 ) ;
44- res . ok ( ) . send ( "Graceful shutdown." ) ;
50+ res . ok ( 200 ) . send ( "Graceful shutdown." ) ;
4551} ) ;
0 commit comments