2023-12-17 03:52:43 +00:00
|
|
|
import {readFileSync} from 'node:fs'
|
|
|
|
import {createServer} from 'node:http'
|
2024-08-18 01:12:10 +00:00
|
|
|
import {argv} from 'node:process'
|
2023-12-17 03:52:43 +00:00
|
|
|
|
2024-08-18 01:12:10 +00:00
|
|
|
const config = {host: '127.0.0.1', port: 9696, filename: argv[2] ?? 'mbchc.mjs'}
|
2024-06-29 17:09:25 +00:00
|
|
|
|
|
|
|
const h_cors = {
|
|
|
|
'Access-Control-Max-Age': '86400',
|
|
|
|
'Access-Control-Allow-Private-Network': 'true',
|
|
|
|
'Access-Control-Allow-Origin': '*',
|
|
|
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
|
|
'Access-Control-Allow-Headers': '*',
|
|
|
|
// 'Access-Control-Allow-Credentials': 'false', // omit this header to disallow
|
|
|
|
}
|
2024-08-18 01:12:10 +00:00
|
|
|
const h_all = {
|
2024-06-29 17:09:25 +00:00
|
|
|
'Content-Type': 'text/javascript',
|
|
|
|
'Cache-Control': 'no-cache',
|
2024-08-18 01:12:10 +00:00
|
|
|
...h_cors
|
|
|
|
}
|
2024-06-29 17:09:25 +00:00
|
|
|
|
2024-08-18 01:12:10 +00:00
|
|
|
/** @type {Record<string,((request: import('node:http').ServerResponse) => void)>} */ const resp = {
|
|
|
|
GET(rx) { rx.writeHead(200, h_all); rx.write(readFileSync(config.filename)) },
|
2024-06-29 17:09:25 +00:00
|
|
|
OPTIONS(rx) { rx.writeHead(204, h_cors) },
|
2023-12-17 03:52:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const server = createServer((rq, rx) => {
|
2024-09-03 16:34:24 +00:00
|
|
|
const handler = resp[rq.method ?? '']
|
|
|
|
handler !== undefined && (new URL(`http://${config.host}:${config.port}${rq.url}`)).pathname === '/' ? handler(rx) : rx.writeHead(400)
|
2024-08-18 01:12:10 +00:00
|
|
|
rx.end(() => void console.log('%s %d %s %s', (new Date()).toISOString(), rx.statusCode, rq.method, rq.url))
|
2023-12-17 03:52:43 +00:00
|
|
|
})
|
2024-08-18 01:12:10 +00:00
|
|
|
server.listen(config.port, config.host, () => void console.log(`Server started at http://${config.host}:${config.port} for ${config.filename}`))
|