From 83da1e4100ae50157d161f2e3e1f024e92e2eeee Mon Sep 17 00:00:00 2001 From: Cris Stringfellow Date: Wed, 15 Jan 2020 00:34:28 +0800 Subject: [PATCH] feat: add killAll function (#186) --- README.md | 12 ++++++++++++ src/chrome-launcher.ts | 24 +++++++++++++++++------- test/chrome-launcher-test.ts | 9 ++++++++- 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a741d0f22..f45e0e285 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,18 @@ Returns an `Array` of paths to available Chrome installations. When `chr Note: This method performs synchronous I/O operations. +### `.killAll()` + +Attempts to kill all Chrome instances created with [`.launch([opts])`](#launchopts). Returns a Promise that resolves to an array of errors that occurred while killing instances. If all instances were killed successfully, the array will be empty. + +```js +const ChromeLauncher = require('chrome-launcher'); + +async function cleanup() { + await ChromeLauncher.killAll(); +} +``` + ## Examples #### Launching chrome: diff --git a/src/chrome-launcher.ts b/src/chrome-launcher.ts index c50c60da6..66ede149a 100644 --- a/src/chrome-launcher.ts +++ b/src/chrome-launcher.ts @@ -57,12 +57,7 @@ export interface ModuleOverrides { } const sigintListener = async () => { - for (const instance of instances) { - try { - await instance.kill(); - } catch (err) { - } - } + await killAll(); process.exit(_SIGINT_EXIT_CODE); }; @@ -90,6 +85,21 @@ async function launch(opts: Options = {}): Promise { return {pid: instance.pid!, port: instance.port!, kill, process: instance.chrome!}; } +async function killAll(): Promise> { + let errors = []; + for (const instance of instances) { + try { + await instance.kill(); + // only delete if kill did not error + // this means erroring instances remain in the Set + instances.delete(instance); + } catch (err) { + errors.push(err); + } + } + return errors; +} + class Launcher { private tmpDirandPidFileReady = false; private pidFile: string; @@ -373,4 +383,4 @@ class Launcher { }; export default Launcher; -export {Launcher, launch}; +export {Launcher, launch, killAll}; diff --git a/test/chrome-launcher-test.ts b/test/chrome-launcher-test.ts index 8005303a9..b2672b670 100644 --- a/test/chrome-launcher-test.ts +++ b/test/chrome-launcher-test.ts @@ -5,7 +5,7 @@ */ 'use strict'; -import {Launcher, Options} from '../src/chrome-launcher'; +import {Launcher, launch, killAll, Options} from '../src/chrome-launcher'; import {DEFAULT_FLAGS} from '../src/flags'; import {spy, stub} from 'sinon'; @@ -98,6 +98,13 @@ describe('Launcher', () => { await chromeInstance.kill(); }); + it('doesn\'t fail when killing all instances', async () => { + await launch(); + await launch(); + const errors = await killAll(); + assert.strictEqual(errors.length, 0); + }); + it('doesn\'t launch multiple chrome processes', async () => { const chromeInstance = new Launcher(); await chromeInstance.launch();