32 lines
1.1 KiB
JavaScript
32 lines
1.1 KiB
JavaScript
/*
|
||
* 本地静态文件服务器(可选工具):node server.mjs [端口]
|
||
* 双击 index.html 即可游玩,无需本服务器;仅当浏览器安全策略限制 file:// 页面时使用。
|
||
*/
|
||
import { createServer } from 'node:http';
|
||
import { readFile } from 'node:fs/promises';
|
||
import { extname, join, resolve } from 'node:path';
|
||
|
||
const root = resolve(process.argv[2] ? '.' : '.');
|
||
const port = Number(process.argv[2]) || 8765;
|
||
|
||
const MIME = {
|
||
'.html': 'text/html; charset=utf-8',
|
||
'.js': 'text/javascript; charset=utf-8',
|
||
'.css': 'text/css; charset=utf-8',
|
||
};
|
||
|
||
createServer(async (req, res) => {
|
||
try {
|
||
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
||
const file = join(root, pathname.endsWith('/') ? join(pathname, 'index.html') : pathname);
|
||
const data = await readFile(file);
|
||
res.writeHead(200, { 'content-type': MIME[extname(file)] || 'application/octet-stream' });
|
||
res.end(data);
|
||
} catch {
|
||
res.writeHead(404);
|
||
res.end('not found');
|
||
}
|
||
}).listen(port, '127.0.0.1', () => {
|
||
console.log(`serving http://127.0.0.1:${port}/`);
|
||
});
|