ampcast/server.js

62 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2024-09-13 07:24:34 +08:00
const path = require('path');
const fs = require('fs');
const http = require('http');
2024-05-03 00:45:03 +08:00
const argv = require('minimist')(process.argv.slice(2));
const {host = 'localhost', port = 8000} = argv;
2024-09-13 07:24:34 +08:00
const wwwDir = path.resolve(__dirname, './app/www');
const devDir = path.resolve(__dirname, './www-dev');
2024-05-03 00:45:03 +08:00
const runtimeDir = argv.dev ? devDir : wwwDir;
2022-12-29 03:21:10 +08:00
2024-09-13 07:24:34 +08:00
const mimeTypes = {
js: 'application/javascript',
json: 'application/json',
ico: 'image/vnd.microsoft.icon',
png: 'image/png',
svg: 'image/svg+xml',
css: 'text/css',
html: 'text/html',
text: 'text/plain',
};
2023-08-10 22:04:04 +08:00
2024-09-13 07:24:34 +08:00
const server = http.createServer(async (req, res) => {
try {
let pathname = req.url.replace(/[?#].*$/, '');
const staticDir = pathname === '/' || /\.(css|js)$/.test(pathname) ? runtimeDir : wwwDir;
if (pathname.endsWith('/')) {
pathname += 'index.html';
}
const filePath = path.join(staticDir, pathname);
const pathTraversal = !filePath.startsWith(staticDir);
const exists =
!pathTraversal &&
2024-09-18 20:43:04 +08:00
(await fs.promises.stat(filePath).then(
(stat) => stat.isFile(),
2024-09-13 07:24:34 +08:00
() => false
));
if (exists) {
const ext = path.extname(pathname).substring(1).toLowerCase();
const mimeType = mimeTypes[ext] || mimeTypes.text;
const stream = fs.createReadStream(filePath);
res.writeHead(200, {'Content-Type': mimeType});
stream.pipe(res);
// console.info(`${req.method} ${req.url} OK`);
} else {
console.warn(`${req.method} ${req.url} NOT FOUND`);
res.writeHead(404, {'Content-Type': mimeTypes.text});
res.end('Not found');
}
} catch (err) {
console.error(`${req.method} ${req.url} ERROR`);
console.error(err);
res.writeHead(500, {'Content-Type': mimeTypes.text});
res.end('Internal server error');
}
});
2021-07-20 09:29:42 +08:00
2024-09-13 07:24:34 +08:00
server.listen(port, host, () => {
2023-06-06 02:03:14 +08:00
const timestamp = new Date().toLocaleString();
2021-07-20 09:29:42 +08:00
console.info(`Serving from: http://${host}:${port}`);
2022-12-29 03:21:10 +08:00
console.info(`Using files from: ${runtimeDir}`);
2021-07-20 09:29:42 +08:00
console.info(`Server started at: ${timestamp}`);
});