commit 69b3c1f251b9a888738bd75f3701b6938e16c663 Author: dab Date: Mon Apr 14 15:20:43 2025 +0000 Add http_server_with_js_build.js diff --git a/http_server_with_js_build.js b/http_server_with_js_build.js new file mode 100644 index 0000000..f302783 --- /dev/null +++ b/http_server_with_js_build.js @@ -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 ` + + + + + + ${PAGE_TITLE} + + + + + +`.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) \ No newline at end of file