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
This commit is contained in:
Tony Sullivan 2022-04-06 15:33:07 +00:00 committed by GitHub
parent ba90ef53d3
commit 9724d844b3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fix bug causing `astro preview` server to close immediately

View file

@ -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);
}

View file

@ -18,6 +18,7 @@ export interface PreviewServer {
host?: string;
port: number;
server: http.Server;
closed(): Promise<void>;
stop(): Promise<void>;
}
@ -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<void>((resolve, reject) => {
httpServer!.addListener('close', resolve);
httpServer!.addListener('error', reject);
})
}
return {
host,
port,
closed,
server: httpServer!,
stop: async () => {
await new Promise((resolve, reject) => {