gerbil/src/main/modules/static-server.ts

56 lines
1.5 KiB
TypeScript

import { createServer, Server } from 'http';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { lookup } from 'mime-types';
import { pathExists } from '@/utils/node/fs';
let server: Server | null = null;
let serverPort = 0;
export const startStaticServer = (distPath: string) =>
new Promise<string>((resolve, reject) => {
server = createServer(async (req, res) => {
const requestPath = req.url === '/' ? 'index.html' : req.url!;
let filePath = join(distPath, requestPath);
if (!(await pathExists(filePath))) {
filePath = join(distPath, 'index.html');
}
try {
const content = await readFile(filePath);
const contentType = lookup(filePath) || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': contentType });
res.end(content);
} catch {
res.writeHead(404);
res.end('Not found');
}
});
server.listen(0, 'localhost', () => {
const address = server!.address();
if (address && typeof address !== 'string') {
serverPort = address.port;
resolve(`http://localhost:${serverPort}`);
} else {
reject(new Error('Failed to start static server'));
}
});
server.on('error', reject);
});
export const stopStaticServer = () =>
new Promise<void>((resolve) => {
if (server) {
server.close(() => {
server = null;
serverPort = 0;
resolve();
});
} else {
resolve();
}
});