diff --git a/docs/getting-started/running-locally.md b/docs/getting-started/running-locally.md index 4e4d3219..667b4b18 100644 --- a/docs/getting-started/running-locally.md +++ b/docs/getting-started/running-locally.md @@ -41,6 +41,12 @@ call in `main.ts` to include an explicit port number: await start(manifest, { port: 3000 }); ``` +You can also change the port by setting the `PORT` environment variable: + +``` +$ PORT=3000 deno task start +``` + Combining all of this we get the following `deno run` command: ``` diff --git a/src/server/mod.ts b/src/server/mod.ts index 149f94a3..4897ec3b 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -67,9 +67,10 @@ export async function createHandler( const ctx = await ServerContext.fromManifest(routes, opts); return ctx.handler(); } + export async function start(routes: Manifest, opts: StartOptions = {}) { const ctx = await ServerContext.fromManifest(routes, opts); - opts.port ??= 8000; + opts.port ??= parseInt(Deno.env.get("PORT") || "8000"); if (opts.experimentalDenoServe === true) { // @ts-ignore as `Deno.serve` is still unstable. await Deno.serve(ctx.handler() as Deno.ServeHandler, opts); diff --git a/tests/main_test.ts b/tests/main_test.ts index 35094aba..b9ddf6fe 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -791,3 +791,46 @@ Deno.test("preloading javascript files", { serverProcess.kill("SIGTERM"); } }); + +Deno.test("PORT environment variable", { + sanitizeOps: false, + sanitizeResources: false, +}, async () => { + const PORT = "8765"; + // Preparation + const serverProcess = new Deno.Command(Deno.execPath(), { + args: [ + "run", + "-A", + "./tests/fixture/main.ts", + ], + stdout: "piped", + stderr: "inherit", + env: { PORT }, + }).spawn(); + + const decoder = new TextDecoderStream(); + const lines = serverProcess.stdout + .pipeThrough(decoder) + .pipeThrough(new TextLineStream()); + + let started = false; + for await (const line of lines) { + if (line.includes("Listening on http://") && line.includes(PORT)) { + started = true; + break; + } + } + if (!started) { + throw new Error("Server didn't start up"); + } + + await delay(100); + + const resp = await fetch("http://localhost:" + PORT); + assert(resp); + assertEquals(resp.status, Status.OK); + + await lines.cancel(); + serverProcess.kill("SIGTERM"); +});