Add http_server_with_js_build.js
This commit is contained in:
commit
69b3c1f251
1 changed files with 68 additions and 0 deletions
68
http_server_with_js_build.js
Normal file
68
http_server_with_js_build.js
Normal file
|
@ -0,0 +1,68 @@
|
||||||
|
/************
|
||||||
|
# Notes
|
||||||
|
|
||||||
|
## Prepare Files
|
||||||
|
- basedir_called_whatever
|
||||||
|
- front
|
||||||
|
- index.js
|
||||||
|
- (optional: node_modules, package.json, ...)
|
||||||
|
- back
|
||||||
|
- http_server_with_js_build.js
|
||||||
|
- (optional: node_modules, package.json, ...)
|
||||||
|
|
||||||
|
## Launch
|
||||||
|
- "bun run" this file (e.g. "bun run ./basedir_called_whatever/back/http_server_with_js_build.js")
|
||||||
|
|
||||||
|
## Env Vars
|
||||||
|
- CTX_WEBSERVER_PAGETITLE
|
||||||
|
- CTX_WEBSERVER_HOST
|
||||||
|
- CTX_WEBSERVER_PORT
|
||||||
|
|
||||||
|
************/
|
||||||
|
|
||||||
|
const async_build_js_script = async (path_js_entry_script, build_options) => {
|
||||||
|
const result = await Bun.build({
|
||||||
|
entrypoints: [ path_js_entry_script ],
|
||||||
|
...build_options,
|
||||||
|
})
|
||||||
|
const str_out = await result.outputs[0].text()
|
||||||
|
return str_out
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE_TITLE = Bun.env['CTX_WEBSERVER_PAGETITLE'] || 'MyCoolWebapp'
|
||||||
|
|
||||||
|
const get_siteroot_html = function () {return `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang=en>
|
||||||
|
<head>
|
||||||
|
<meta charset=utf-8>
|
||||||
|
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'/>">
|
||||||
|
<title>${PAGE_TITLE}</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="text/javascript" src="/index.js">
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`.trim()}
|
||||||
|
|
||||||
|
const server = Bun.serve({
|
||||||
|
hostname: Bun.env['CTX_WEBSERVER_HOST'] || '127.0.0.1',
|
||||||
|
port : Bun.env['CTX_WEBSERVER_PORT'] ? parseInt(Bun.env['CTX_WEBSERVER_PORT']) : 1211,
|
||||||
|
async fetch (req, server) {
|
||||||
|
let resp = new Response(null, { status: 404 })
|
||||||
|
const url = new URL(req.url)
|
||||||
|
if (url.pathname === '/') {
|
||||||
|
resp = new Response(get_siteroot_html(), { status: 200, headers: { 'Content-Type': 'text/html' } })
|
||||||
|
}
|
||||||
|
else if (url.pathname === '/index.js') {
|
||||||
|
resp = new Response(
|
||||||
|
await async_build_js_script(import.meta.dir + '/../front/index.js'),
|
||||||
|
{ status: 200, headers: { 'Content-Type': 'text/javascript' } }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return resp
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
console.info(server)
|
Reference in a new issue