fix(cli): dev/dev:offline Ctrl-C 退出防重入并支持二次强制退出
This commit is contained in:
@@ -6,12 +6,35 @@ const { startServer } = require('./serve-dist');
|
||||
|
||||
const log = createLogger('dev');
|
||||
let serverRef = null;
|
||||
let shuttingDown = false;
|
||||
|
||||
function runNode(scriptPath) {
|
||||
const result = spawnSync(process.execPath, [scriptPath], { stdio: 'inherit' });
|
||||
return result && Number.isFinite(result.status) ? result.status : 1;
|
||||
}
|
||||
|
||||
function closeServer(server, exitCode) {
|
||||
if (!server) {
|
||||
process.exit(exitCode);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections();
|
||||
if (typeof server.closeAllConnections === 'function') server.closeAllConnections();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
const forceTimer = setTimeout(() => process.exit(exitCode), 2000);
|
||||
if (typeof forceTimer.unref === 'function') forceTimer.unref();
|
||||
|
||||
server.close(() => {
|
||||
clearTimeout(forceTimer);
|
||||
process.exit(exitCode);
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const elapsedMs = startTimer();
|
||||
log.info('开始', { version: process.env.npm_package_version });
|
||||
@@ -45,13 +68,21 @@ async function main() {
|
||||
|
||||
log.ok('就绪', { ms: elapsedMs(), url: `http://localhost:${actualPort}` });
|
||||
|
||||
const shutdown = () => {
|
||||
log.info('正在关闭...');
|
||||
if (!serverRef) process.exit(0);
|
||||
serverRef.close(() => process.exit(0));
|
||||
const shutdown = (signal) => {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
process.stdout.write('\n');
|
||||
log.info('正在关闭...', { signal });
|
||||
|
||||
process.once('SIGINT', () => process.exit(130));
|
||||
|
||||
const exit = signal === 'SIGINT' ? 130 : 0;
|
||||
closeServer(serverRef, exit);
|
||||
};
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
|
||||
process.once('SIGINT', () => shutdown('SIGINT'));
|
||||
process.once('SIGTERM', () => shutdown('SIGTERM'));
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
|
||||
Reference in New Issue
Block a user