From 934f89379102e78d628eaa6c514b869b86b95770 Mon Sep 17 00:00:00 2001 From: Mark Hanna Date: Tue, 23 Jul 2024 12:22:21 +1200 Subject: [PATCH] Added `.env` initialisation --- scripts/getEnv.ts | 27 +++++++++++++++++++++++++++ scripts/server.ts | 16 ++++++++++++---- 2 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 scripts/getEnv.ts diff --git a/scripts/getEnv.ts b/scripts/getEnv.ts new file mode 100644 index 0000000..dbe0c25 --- /dev/null +++ b/scripts/getEnv.ts @@ -0,0 +1,27 @@ +import { writeFileSync } from 'node:fs'; + +import dotenv from 'dotenv'; + +import packageJson from '../package.json' with { type: 'json' }; + +const defaultEnv = `PROJECT_NAME = "${packageJson.name}" +MODE = "development" +PORT = "8080"`; + +function init() { + try { + // If no .env file exists, create one first + writeFileSync('.env', defaultEnv, { flag: 'wx' }); + console.log('Creating default .env file'); + } catch (e) { + // If a .env file exists, just continue + } + + dotenv.config(); +} + +export function getEnv(): Partial> { + init(); + + return process.env; +} diff --git a/scripts/server.ts b/scripts/server.ts index 020c095..db45064 100644 --- a/scripts/server.ts +++ b/scripts/server.ts @@ -1,16 +1,16 @@ import { dirname, join } from 'path'; import { fileURLToPath } from 'url'; -import dotenv from 'dotenv'; import express from 'express'; +import { getEnv } from './getEnv.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); -dotenv.config(); const app = express(); -const port = process.env.PORT; -const projectName = process.env.PROJECT_NAME; +const env = getEnv(); +const port = Number(env.PORT); +const projectName = env.PROJECT_NAME; if (projectName) { // GitHub Pages publishes projects to .github.io/ @@ -47,5 +47,13 @@ app.get('*', (request, response, next) => { response.status(404).sendFile(join(__dirname, '../app/404.html')); }); +if (typeof port === 'undefined') { + throw new Error('Cannot listen on undefined port'); +} + +if (isNaN(port)) { + throw new Error('Cannot listen to NaN port'); +} + app.listen(port, () => {}); console.log(`Listening on port ${port}`);