feat: 搭建前后端可执行程序示例
This commit is contained in:
39
src/server/config.ts
Normal file
39
src/server/config.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
export interface RuntimeConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
}
|
||||
|
||||
const DEFAULT_HOST = "127.0.0.1";
|
||||
const DEFAULT_PORT = 3000;
|
||||
|
||||
export function readRuntimeConfig(
|
||||
argv: string[] = process.argv.slice(2),
|
||||
env: Record<string, string | undefined> = Bun.env,
|
||||
): RuntimeConfig {
|
||||
const host = readOption(argv, "host") ?? env.HOST ?? DEFAULT_HOST;
|
||||
const portValue = readOption(argv, "port") ?? env.PORT ?? String(DEFAULT_PORT);
|
||||
const port = Number(portValue);
|
||||
|
||||
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
||||
throw new Error(`无效端口: ${portValue}`);
|
||||
}
|
||||
|
||||
return { host, port };
|
||||
}
|
||||
|
||||
function readOption(argv: string[], name: string): string | undefined {
|
||||
const prefix = `--${name}=`;
|
||||
const inline = argv.find((value) => value.startsWith(prefix));
|
||||
|
||||
if (inline) {
|
||||
return inline.slice(prefix.length);
|
||||
}
|
||||
|
||||
const index = argv.indexOf(`--${name}`);
|
||||
|
||||
if (index >= 0) {
|
||||
return argv[index + 1];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
Reference in New Issue
Block a user