2023-01-05 05:25:27 +00:00
|
|
|
import { mustDefault } from '@apextoaster/js-utils';
|
2023-01-05 03:55:25 +00:00
|
|
|
import { readFile } from 'fs';
|
|
|
|
import { createServer } from 'http';
|
|
|
|
import { join } from 'path';
|
|
|
|
|
2023-01-05 05:25:27 +00:00
|
|
|
const { env } = process;
|
|
|
|
|
2023-01-08 15:46:13 +00:00
|
|
|
const host = mustDefault(env.ONNX_WEB_DEV_HOST, '127.0.0.1');
|
2023-01-05 05:25:27 +00:00
|
|
|
const port = mustDefault(env.ONNX_WEB_DEV_PORT, '3000');
|
2023-01-05 03:55:25 +00:00
|
|
|
const root = process.cwd();
|
|
|
|
|
2023-01-05 05:25:27 +00:00
|
|
|
const portNum = parseInt(port, 10);
|
|
|
|
|
2023-01-05 16:39:46 +00:00
|
|
|
const contentTypes = [
|
|
|
|
[/^.*\.html$/, 'text/html'],
|
|
|
|
[/^.*\.js$/, 'application/javascript'],
|
|
|
|
[/^.*\.json$/, 'text/json'],
|
|
|
|
];
|
|
|
|
|
|
|
|
function getContentType(path) {
|
|
|
|
for (const [regex, type] of contentTypes) {
|
|
|
|
if (regex.test(path)) {
|
|
|
|
return type;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return 'unknown';
|
|
|
|
}
|
|
|
|
|
2023-01-05 03:55:25 +00:00
|
|
|
const server = createServer((req, res) => {
|
2023-01-05 16:39:46 +00:00
|
|
|
const path = join(root, 'out', req.url || 'index.html');
|
|
|
|
readFile(path, function (err, data) {
|
2023-01-05 03:55:25 +00:00
|
|
|
if (err) {
|
|
|
|
res.writeHead(404);
|
|
|
|
res.end(JSON.stringify(err));
|
|
|
|
return;
|
|
|
|
}
|
2023-01-05 16:39:46 +00:00
|
|
|
res.writeHead(200, {
|
|
|
|
'Content-Type': getContentType(path),
|
|
|
|
});
|
2023-01-05 03:55:25 +00:00
|
|
|
res.end(data);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2023-01-05 05:25:27 +00:00
|
|
|
server.listen(portNum, host, () => {
|
|
|
|
console.log(`Dev server running at http://${host}:${port}/index.html`);
|
2023-01-05 03:55:25 +00:00
|
|
|
});
|