Skip to content

Commit

Permalink
feat: stop spinner on process exit
Browse files Browse the repository at this point in the history
Stops the spinner when `SIGTERM` or `SIGINT` is received.
  • Loading branch information
43081j committed Nov 3, 2024
1 parent 5b5fba6 commit 36a03a4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as constants from './constants';
import {countLines} from './string-lines';
import process from 'node:process';

export type Formatter = (input: string) => string;

Expand Down Expand Up @@ -49,6 +50,7 @@ export class Spinner {
if (process.stdout.getWindowSize) this.terminalWidth = process.stdout.getWindowSize()[0];
this.currentSymbol = this.frames[0];
this.framesLineCountCache.fill(-1);
this.addListeners();
}

tick() {
Expand All @@ -64,6 +66,22 @@ export class Spinner {
process.stdout.write(constants.CLEAR_LINE);
}

private onProcessExit = () => {
if (this.running) {
this.stop();
}
};

private addListeners() {
process.once('SIGTERM', this.onProcessExit);
process.once('SIGINT', this.onProcessExit);
}

private clearListeners() {
process.off('SIGTERM', this.onProcessExit);
process.off('SIGINT', this.onProcessExit);
}

private getLineCount(output: string) {
let amount = this.framesLineCountCache[this.frameIndex];
if (amount !== -1) return amount;
Expand Down Expand Up @@ -128,6 +146,7 @@ export class Spinner {
stop() {
this.clearMultiLineOutput();
this.end(false);
this.clearListeners();
}

private end(newLine = true) {
Expand Down
13 changes: 13 additions & 0 deletions src/test/spinner-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {test} from 'node:test';
import {Spinner, Symbols} from '..';
import {createFinishingRenderedLine, createRenderedLine, interceptStdout} from './utils.js';
import * as constants from '../constants';
import process from 'node:process';

async function testEndMethod(method: keyof Symbols, type: 'str' | 'obj', customSymbol?: string) {
const stdout = await interceptStdout(async () => {
Expand Down Expand Up @@ -60,6 +61,18 @@ test('end methods', async (t) => {

assert.equal(stdout, createFinishingRenderedLine('', ''));
});

await t.test('process exit', async () => {
const stdout = await interceptStdout(async () => {
const spinner = new Spinner();
spinner.start();
// TODO (43081j): maybe this'll spook other things? if something is
// listening for SIGTERM
process.emit('SIGTERM');
});

assert.equal(stdout, constants.CLEAR_LINE + constants.SHOW_CURSOR);
});
});

async function testSpinner(frames?: string[], text?: string, symbolFormatter?: (v: string) => string) {
Expand Down

0 comments on commit 36a03a4

Please sign in to comment.