Skip to content

Instantly share code, notes, and snippets.

@Leedehai
Last active March 24, 2022 00:33
Show Gist options
  • Save Leedehai/efe55619339157e883a6bb49286a5c37 to your computer and use it in GitHub Desktop.
Save Leedehai/efe55619339157e883a6bb49286a5c37 to your computer and use it in GitHub Desktop.
Static server that mimics GitHub Pages.
// Static server that mimics GitHub Pages.
import chalk from 'chalk';
import express from 'express';
import * as fs from 'fs';
import http from 'http';
import path from 'path';
import {fileURLToPath} from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SERVE_ROOT = path.join(__dirname);
const ERROR_PAGE_PATH = '404.html';
const PORT_NUMBER = 8080;
function logRequest(req) {
const timeStr = new Date().toLocaleTimeString('en-US', {hour12: false});
console.log(`[${timeStr}] ${req.method} ${req.path}`);
}
function logResponse(resp) {
const statusOk = resp.statusCode >= 200 && resp.statusCode < 300;
const statusMessage =
resp.statusMessage || http.STATUS_CODES[resp.statusCode];
const style = statusOk ? chalk.green : chalk.red;
console.log(style(`> ${resp.statusCode} ${statusMessage}`));
}
const app = express();
app.use((req, resp, next) => {
logRequest(req);
const requestedFilePath = path.join(SERVE_ROOT, req.path);
if (fs.existsSync(requestedFilePath)) {
resp.status(200).sendFile(requestedFilePath);
} else {
resp.status(404).sendFile(ERROR_PAGE_PATH, {root: SERVE_ROOT});
}
logResponse(resp);
});
app.listen(PORT_NUMBER, () => {
console.log(chalk.underline(`Server is running at localhost:${PORT_NUMBER}`));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment