This repository has been archived on 2025-06-06. You can view files and clone it, but cannot push or open issues or pull requests.
bun_examples/http_server_with_js_build.js

68 lines
No EOL
1.7 KiB
JavaScript

/************
# 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)