1+ import shutdownServer from 'http-graceful-shutdown' ;
2+ import express from 'express' ;
3+ import fs from 'fs' ;
4+
5+ //
16// this file will be glued to the top of the specific xy-serve.js file
7+ //
8+
29const debug_serve = false ; // set to true for debug log output in node process
3- const shutdownServer = require ( "http-graceful-shutdown" ) ;
4- const express = require ( "express" ) ;
510const app = express ( ) ;
611
712app . use ( express . json ( { limit : "50mb" } ) ) ;
813
9- const fs = require ( "fs" ) ;
10-
1114function debugLog ( ) {
1215 if ( debug_serve ) {
1316 console . log . apply ( this , arguments )
1417 }
1518}
1619
1720function getInstanceId ( ) {
18- const args = process . argv . slice ( 2 ) ;
19-
2021 // Look for the --node-server-instance-id option
2122 let instanceId ;
22-
23- args . forEach ( arg => {
23+ process . argv . slice ( 2 ) . forEach ( arg => {
2424 if ( arg . startsWith ( '--node-server-instance-id=' ) ) {
2525 instanceId = arg . split ( '=' ) [ 1 ] ;
2626 }
@@ -33,31 +33,30 @@ function getInstanceId() {
3333 return instanceId ;
3434}
3535
36- var listener = app . listen ( 0 , "127.0.0.1" , ( ) => {
36+ let listener = app . listen ( 0 , "127.0.0.1" , ( ) => {
3737 const instanceId = getInstanceId ( ) ;
3838 debugLog ( "Server running on port " + listener . address ( ) . port + " for instance " + instanceId ) ;
3939 fs . writeFile ( "server.port.tmp" , "" + listener . address ( ) . port , function ( err ) {
4040 if ( err ) {
4141 return console . log ( err ) ;
4242 } else {
43- fs . rename ( "server.port.tmp" , `server-${ instanceId } .port` , function ( err ) {
43+ fs . rename ( "server.port.tmp" , `server-${ instanceId } .port` , function ( err ) { // try to be as atomic as possible
4444 if ( err ) {
4545 return console . log ( err ) ;
4646 }
47- } ) ; // try to be as atomic as possible
47+ } ) ;
4848 }
4949 } ) ;
5050} ) ;
51- const shutdown = shutdownServer ( listener , {
52- forceExit : false , // let the event loop clear
53- finally : ( ) => debugLog ( "graceful shutdown finished." ) ,
54- } ) ;
5551
5652app . post ( "/shutdown" , ( req , res ) => {
5753 res . status ( 200 ) . send ( "Shutting down" ) ;
5854 setTimeout ( async ( ) => {
5955 try {
60- await shutdown ( ) ;
56+ await shutdownServer ( listener , {
57+ forceExit : false , // let the event loop clear
58+ finally : ( ) => debugLog ( "graceful shutdown finished." ) ,
59+ } ) ( ) ;
6160 } catch ( err ) {
6261 console . error ( "Error during shutdown:" , err ) ;
6362 }
0 commit comments