Skip to content

Commit

Permalink
Fix gracefulExit() (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
jakobo authored Oct 16, 2022
1 parent b144dda commit 64e5907
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
5 changes: 5 additions & 0 deletions fixture-async.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import process from 'node:process';
import exitHook, {asyncExitHook, gracefulExit} from './index.js';

exitHook(() => {
Expand Down Expand Up @@ -29,4 +30,8 @@ asyncExitHook(
},
);

if (process.env.EXIT_HOOK_SYNC === '1') {
process.exit(0); // eslint-disable-line unicorn/no-process-exit
}

gracefulExit();
12 changes: 6 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ let isCalled = false;
let isRegistered = false;

async function exit(shouldManuallyExit, isSynchronous, signal) {
if (isCalled) {
return;
}

isCalled = true;

if (asyncCallbacks.size > 0 && isSynchronous) {
console.error([
'SYNCHRONOUS TERMINATION NOTICE:',
Expand All @@ -17,12 +23,6 @@ async function exit(shouldManuallyExit, isSynchronous, signal) {
].join(' '));
}

if (isCalled) {
return;
}

isCalled = true;

const done = (force = false) => {
if (force === true || shouldManuallyExit === true) {
process.exit(128 + signal); // eslint-disable-line unicorn/no-process-exit
Expand Down
16 changes: 14 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,25 @@ import execa from 'execa';
import exitHook, {asyncExitHook} from './index.js';

test('main', async t => {
const {stdout} = await execa(process.execPath, ['fixture.js']);
const {stdout, stderr} = await execa(process.execPath, ['fixture.js']);
t.is(stdout, 'foo\nbar');
t.is(stderr, '');
});

test('main-async', async t => {
const {stdout} = await execa(process.execPath, ['fixture-async.js']);
const {stdout, stderr} = await execa(process.execPath, ['fixture-async.js']);
t.is(stdout, 'foo\nbar\nquux');
t.is(stderr, '');
});

test('main-async-notice', async t => {
const {stdout, stderr} = await execa(process.execPath, ['fixture-async.js'], {
env: {
EXIT_HOOK_SYNC: '1',
},
});
t.is(stdout, 'foo\nbar');
t.regex(stderr, /SYNCHRONOUS TERMINATION NOTICE/);
});

test('listener count', t => {
Expand Down

0 comments on commit 64e5907

Please sign in to comment.