feat: use PORT environment variable to change port (#468)
This can be useful when deploying to other providers. Also more convenient for projects with multiple developers with port preferences --------- Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
This commit is contained in:
co-authored by
Asher Gomez
parent
65e6385bc4
commit
6e1874ccca
@@ -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:
|
||||
|
||||
```
|
||||
|
||||
+2
-1
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user