From b7248995ab3ce21357fe66f641605fec8d9337e7 Mon Sep 17 00:00:00 2001 From: Edgar HIPP Date: Thu, 23 Aug 2018 11:26:54 +0200 Subject: [PATCH] Fix SIGINT handling to work even if server not yet ready --- bin/webpack-dev-server.js | 23 ++++++++++++++--------- test/cli.test.js | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/bin/webpack-dev-server.js b/bin/webpack-dev-server.js index 4f5f655a7f..7736a03dd8 100755 --- a/bin/webpack-dev-server.js +++ b/bin/webpack-dev-server.js @@ -15,6 +15,20 @@ const addDevServerEntrypoints = require('../lib/util/addDevServerEntrypoints'); const createDomain = require('../lib/util/createDomain'); // eslint-disable-line const createLog = require('../lib/createLog'); +let server; + +['SIGINT', 'SIGTERM'].forEach((sig) => { + process.on(sig, () => { + if (server) { + server.close(() => { + process.exit(); // eslint-disable-line no-process-exit + }); + } else { + process.exit(); // eslint-disable-line no-process-exit + } + }); +}); + // Prefer the local installation of webpack-dev-server if (importLocal(__filename)) { debug('Using local install of webpack-dev-server'); @@ -392,7 +406,6 @@ function startDevServer(webpackOptions, options) { const suffix = (options.inline !== false || options.lazy === true ? '/' : '/webpack-dev-server/'); - let server; try { server = new Server(compiler, options, log); } catch (e) { @@ -404,14 +417,6 @@ function startDevServer(webpackOptions, options) { throw e; } - ['SIGINT', 'SIGTERM'].forEach((sig) => { - process.on(sig, () => { - server.close(() => { - process.exit(); // eslint-disable-line no-process-exit - }); - }); - }); - if (options.socket) { server.listeningApp.on('error', (e) => { if (e.code === 'EADDRINUSE') { diff --git a/test/cli.test.js b/test/cli.test.js index 18c025ce0c..33e3d38ab8 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -46,4 +46,25 @@ describe('CLI', () => { done(); }); }).timeout(18000); + + it('should exit the process when SIGINT is detected, even before the compilation is done', (done) => { + const cliPath = path.resolve(__dirname, '../bin/webpack-dev-server.js'); + const examplePath = path.resolve(__dirname, '../examples/cli/public'); + const nodePath = execa.shellSync('which node').stdout; + + const proc = execa(nodePath, [cliPath], { cwd: examplePath }); + + let killed = false; + proc.stdout.on('data', () => { + if (!killed) { + assert(proc.pid !== 0); + proc.kill('SIGINT'); + } + killed = true; + }); + + proc.on('exit', () => { + done(); + }); + }).timeout(18000); });