From 9724d844b32fb30c91ec3d060421bbb0cc36428a Mon Sep 17 00:00:00 2001 From: Tony Sullivan Date: Wed, 6 Apr 2022 15:33:07 +0000 Subject: [PATCH] fix(#2981): keeps `astro preview` server alive (#3004) * fix(#2981): keeps server alive * chore: adding changeset * keep alive until the 'close' or 'error' event fires --- .changeset/big-yaks-invite.md | 5 +++++ packages/astro/src/cli/index.ts | 3 ++- packages/astro/src/core/preview/index.ts | 10 ++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 .changeset/big-yaks-invite.md diff --git a/.changeset/big-yaks-invite.md b/.changeset/big-yaks-invite.md new file mode 100644 index 000000000..bbedfd0f1 --- /dev/null +++ b/.changeset/big-yaks-invite.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix bug causing `astro preview` server to close immediately diff --git a/packages/astro/src/cli/index.ts b/packages/astro/src/cli/index.ts index 50ef47531..df2d2c2a8 100644 --- a/packages/astro/src/cli/index.ts +++ b/packages/astro/src/cli/index.ts @@ -138,7 +138,8 @@ export async function cli(args: string[]) { case 'preview': { try { - return await preview(config, { logging }); // this will keep running + const server = await preview(config, { logging }); + return await server.closed(); // keep alive until the server is closed } catch (err) { return throwAndExit(err); } diff --git a/packages/astro/src/core/preview/index.ts b/packages/astro/src/core/preview/index.ts index 1d68bd0f1..9040e6581 100644 --- a/packages/astro/src/core/preview/index.ts +++ b/packages/astro/src/core/preview/index.ts @@ -18,6 +18,7 @@ export interface PreviewServer { host?: string; port: number; server: http.Server; + closed(): Promise; stop(): Promise; } @@ -133,9 +134,18 @@ export default async function preview( // Start listening on `hostname:port`. await startServer(startServerTime); + // Resolves once the server is closed + function closed() { + return new Promise((resolve, reject) => { + httpServer!.addListener('close', resolve); + httpServer!.addListener('error', reject); + }) + } + return { host, port, + closed, server: httpServer!, stop: async () => { await new Promise((resolve, reject) => {