27 lines
1.8 KiB
JavaScript
27 lines
1.8 KiB
JavaScript
import http from 'node:http';
|
||
import { readFile, stat } from 'node:fs/promises';
|
||
import path from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
const args = process.argv.slice(2);
|
||
const arg = (name, fallback) => { const index = args.indexOf(name); return index < 0 ? fallback : args[index + 1]; };
|
||
const port = Number(arg('--port', process.env.PORT || '5173'));
|
||
const host = arg('--host', '127.0.0.1');
|
||
const root = path.resolve(fileURLToPath(new URL('../', import.meta.url)));
|
||
const publicFiles = new Set(['index.html', 'favicon.svg', 'src/styles.css', 'src/apps.mjs', 'src/main.mjs']);
|
||
const types = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.svg': 'image/svg+xml' };
|
||
const server = http.createServer(async (request, response) => {
|
||
if (!['GET', 'HEAD'].includes(request.method)) { response.writeHead(405, { Allow: 'GET, HEAD' }); response.end(); return; }
|
||
try {
|
||
const url = new URL(request.url, 'http://localhost');
|
||
const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '') || 'index.html';
|
||
if (!publicFiles.has(relative)) { response.writeHead(404); response.end('Not found'); return; }
|
||
const file = path.resolve(root, relative);
|
||
if (!(await stat(file)).isFile()) throw new Error('Not a file');
|
||
response.writeHead(200, { 'Content-Type': types[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
||
response.end(request.method === 'HEAD' ? undefined : await readFile(file));
|
||
} catch { response.writeHead(404); response.end('Not found'); }
|
||
});
|
||
server.on('error', error => { console.error(`启动失败:${error.message}`); process.exitCode = 1; });
|
||
server.listen(port, host, () => console.log(`蝶雅产品AI中心:http://${host}:${port}`));
|