Skip to content

Commit

Permalink
fix(watch): wait for the process to exit
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber committed Aug 31, 2023
1 parent a4bd761 commit 592965a
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/watch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,17 @@ export const watchCommand = command({

let runProcess: ChildProcess | undefined;

const reRun = debounce(() => {
const reRun = debounce(async () => {
if (
runProcess
&& (!runProcess.killed && runProcess.exitCode === null)
) {
const waitForExit = new Promise((resolve) => {
runProcess!.on('exit', resolve);
});
runProcess.kill();

await waitForExit;
}

// Not first run
Expand Down
44 changes: 44 additions & 0 deletions tests/specs/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,50 @@ export default testSuite(async ({ describe }, fixturePath: string) => {
await tsxProcess;
}, 10_000);

test('wait for exit', async ({ onTestFinish }) => {
const fixture = await createFixture({
'index.js': `
console.log('start');
const sleepSync = (delay) => {
const waitTo = Date.now() + delay;
while (Date.now() < waitTo) {}
};
process.on('exit', () => {
sleepSync(300);
console.log('end');
});
`,
});

onTestFinish(async () => await fixture.rm());

const tsxProcess = tsx({
args: [
'watch',
path.join(fixture.path, 'index.js'),
],
});

const stdout = await new Promise<string>((resolve) => {
const buffers: Buffer[] = [];
async function onStdOut(data: Buffer) {
buffers.push(data);
const chunkString = data.toString();
if (chunkString.match('start\n')) {
tsxProcess.stdin?.write('enter');
} else if (chunkString.match('end\n')) {
tsxProcess.kill();
resolve(Buffer.concat(buffers).toString());
}
}

tsxProcess.stdout!.on('data', onStdOut);
tsxProcess.stderr!.on('data', onStdOut);
});

expect(stdout).toBe('\u001Bcstart\nend\n');
}, 10_000);

describe('help', ({ test }) => {
test('shows help', async () => {
const tsxProcess = await tsx({
Expand Down

0 comments on commit 592965a

Please sign in to comment.