From 4b82f4f8639282ef5b9af1411fb43dde620d8ba8 Mon Sep 17 00:00:00 2001 From: Harry Chen Date: Thu, 16 May 2024 13:35:50 +0800 Subject: [PATCH] feat: add keepalive args (#22) --- README.md | 3 +++ lib/constants.js | 1 + lib/process.js | 23 ++++++++++++++++++++++- lib/wrap.js | 15 +++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 lib/constants.js diff --git a/README.md b/README.md index 1b1e9f0..e819763 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,9 @@ $ npx mwtsc --watch --run ./bootstrap.js # run with tsc options $ npx mwtsc --watch --project tsconfig.production.json --run ./bootstrap.js + +# the child process keep avaliable during the development +$ npx mwtsc --watch --run ./bootstrap.js --keepalive ``` ## Different with tsc and tsc-watch diff --git a/lib/constants.js b/lib/constants.js new file mode 100644 index 0000000..fdc3e75 --- /dev/null +++ b/lib/constants.js @@ -0,0 +1 @@ +exports.CHILD_PROCESS_EXCEPTION_EXIT_CODE = 10; diff --git a/lib/process.js b/lib/process.js index d4a8007..b06073f 100644 --- a/lib/process.js +++ b/lib/process.js @@ -1,5 +1,6 @@ const { fork, spawn } = require('child_process'); -const { filterFileChangedText, debug } = require('./util'); +const { filterFileChangedText, debug, output, colors } = require('./util'); +const { CHILD_PROCESS_EXCEPTION_EXIT_CODE } = require('./constants'); // is windows const isWin = process.platform === 'win32'; @@ -110,6 +111,26 @@ const forkRun = (runCmdPath, runArgs = [], options = {}) => { } }; runChild.on('message', onServerReady); + if (runArgs.includes('--keepalive')) { + runChild.once('exit', code => { + if (code === CHILD_PROCESS_EXCEPTION_EXIT_CODE) { + output(colors.red('*'.repeat(120))); + output( + `A ${colors.red( + `${colors.bright( + 'Critical unhandledRejection or uncaughtException' + )}` + )} was detected and the process has exited automatically.` + ); + output('Please make sure to handle it.'); + output( + 'The --keepalive parameter was enabled, we will do our best to ensure the process remains normal..' + ); + output(colors.red('*'.repeat(120))); + innerFork(false); + } + }); + } } innerFork(true); diff --git a/lib/wrap.js b/lib/wrap.js index 6f16dba..0be2076 100644 --- a/lib/wrap.js +++ b/lib/wrap.js @@ -2,6 +2,21 @@ const childPath = process.env.CHILD_CMD_PATH; const childCwd = process.env.CHILD_CWD; const { join, isAbsolute } = require('path'); +const { CHILD_PROCESS_EXCEPTION_EXIT_CODE } = require('./constants'); + +// get the child process execArgs +const runArgs = process.argv.slice(2); +if (runArgs.includes('--keepalive')) { + process.once('unhandledRejection', err => { + console.error(err); + process.exit(CHILD_PROCESS_EXCEPTION_EXIT_CODE); + }); + + process.once('uncaughtException', err => { + console.error(err); + process.exit(CHILD_PROCESS_EXCEPTION_EXIT_CODE); + }); +} process.on('message', data => { if (data.title === 'server-kill') {