Skip to content

Commit

Permalink
Added .env initialisation
Browse files Browse the repository at this point in the history
  • Loading branch information
Mark Hanna committed Jul 23, 2024
1 parent af3e6b4 commit 934f893
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
27 changes: 27 additions & 0 deletions scripts/getEnv.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, string>> {
init();

return process.env;
}
16 changes: 12 additions & 4 deletions scripts/server.ts
Original file line number Diff line number Diff line change
@@ -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 <username>.github.io/<projectname>
Expand Down Expand Up @@ -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}`);

0 comments on commit 934f893

Please sign in to comment.