Add rudimentary command line parsing to express app

This commit is contained in:
2026-01-01 14:34:16 -06:00
parent db81129724
commit c330da49fc
3 changed files with 54 additions and 2 deletions

View File

@@ -3,6 +3,7 @@ import express, {
Response as ExpressResponse, Response as ExpressResponse,
} from "express"; } from "express";
import { match } from "path-to-regexp"; import { match } from "path-to-regexp";
import { cli } from "./cli";
import { contentTypes } from "./content-types"; import { contentTypes } from "./content-types";
import { httpCodes } from "./http-codes"; import { httpCodes } from "./http-codes";
import { routes } from "./routes"; import { routes } from "./routes";
@@ -117,4 +118,6 @@ app.use(async (req: ExpressRequest, res: ExpressResponse) => {
res.status(code).send(result); 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}`);
});

49
express/cli.ts Normal file
View File

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

View File

@@ -6,4 +6,4 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$DIR" cd "$DIR"
exec ../cmd node dist/index.js exec ../cmd node dist/index.js "$@"