From c330da49fc5404d3ff7f63288f2a2b3e5b918691 Mon Sep 17 00:00:00 2001 From: Michael Wolf Date: Thu, 1 Jan 2026 14:34:16 -0600 Subject: [PATCH] Add rudimentary command line parsing to express app --- express/app.ts | 5 ++++- express/cli.ts | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ express/run.sh | 2 +- 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 express/cli.ts diff --git a/express/app.ts b/express/app.ts index 2e14203..d91a654 100644 --- a/express/app.ts +++ b/express/app.ts @@ -3,6 +3,7 @@ import express, { Response as ExpressResponse, } from "express"; import { match } from "path-to-regexp"; +import { cli } from "./cli"; import { contentTypes } from "./content-types"; import { httpCodes } from "./http-codes"; import { routes } from "./routes"; @@ -117,4 +118,6 @@ app.use(async (req: ExpressRequest, res: ExpressResponse) => { res.status(code).send(result); }); -app.listen(3000); +app.listen(cli.listen.port, cli.listen.host, () => { + console.log(`Listening on ${cli.listen.host}:${cli.listen.port}`); +}); diff --git a/express/cli.ts b/express/cli.ts new file mode 100644 index 0000000..dcfa6f8 --- /dev/null +++ b/express/cli.ts @@ -0,0 +1,49 @@ +import { parseArgs } from "node:util"; + +const { values } = parseArgs({ + options: { + listen: { + type: "string", + short: "l", + }, + }, + strict: true, + allowPositionals: false, +}); + +function parseListenAddress(listen: string | undefined): { + host: string; + port: number; +} { + const defaultHost = "127.0.0.1"; + const defaultPort = 3000; + + if (!listen) { + return { host: defaultHost, port: defaultPort }; + } + + const lastColon = listen.lastIndexOf(":"); + if (lastColon === -1) { + // Just a port number + const port = parseInt(listen, 10); + if (isNaN(port)) { + throw new Error(`Invalid listen address: ${listen}`); + } + return { host: defaultHost, port }; + } + + const host = listen.slice(0, lastColon); + const port = parseInt(listen.slice(lastColon + 1), 10); + + if (isNaN(port)) { + throw new Error(`Invalid port in listen address: ${listen}`); + } + + return { host, port }; +} + +const listenAddress = parseListenAddress(values.listen); + +export const cli = { + listen: listenAddress, +}; diff --git a/express/run.sh b/express/run.sh index 3fbad7d..45e91bb 100755 --- a/express/run.sh +++ b/express/run.sh @@ -6,4 +6,4 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd "$DIR" -exec ../cmd node dist/index.js +exec ../cmd node dist/index.js "$@"