Last active
November 9, 2024 18:47
-
-
Save riziles/82c3dc4f28c5c0aa4812ea3d15f73b5c to your computer and use it in GitHub Desktop.
Node.js script to render html with Lit SSR, serve with Express and open in browser with `open`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import open from 'open' | |
| import { apps } from 'open' | |
| import express from 'express' | |
| import { html } from 'lit-html/static.js' | |
| import { render } from '@lit-labs/ssr' | |
| import { collectResultSync } from '@lit-labs/ssr/lib/render-result.js' | |
| const render2 = x => collectResultSync(render(x)) | |
| const app = express() | |
| const port = 0 | |
| app.get('/', (req, res) => { | |
| const some_random_number = Math.random() | |
| res.send( | |
| render2(html` | |
| <!DOCTYPE html> | |
| <html> | |
| <body> | |
| <p> | |
| Sample node.js app. Should automatically shut down back end when | |
| window closes. | |
| </p> | |
| <p>Some random number: ${some_random_number}</p> | |
| <script type="text/javascript"> | |
| window.addEventListener('beforeunload', function (e) { | |
| e.preventDefault() | |
| e.returnValue = '' | |
| fetch('/close') | |
| }) | |
| </script> | |
| </body> | |
| </html> | |
| `) | |
| ) | |
| }) | |
| app.get('/close', (req, res) => { | |
| handler() | |
| res.send( | |
| render2( | |
| html`<html> | |
| Shutting down server... | |
| </html>` | |
| ) | |
| ) | |
| }) | |
| const server = app.listen(port, () => { | |
| console.log(`Example app listening on port ${server.address().port}`) | |
| ui(server.address().port) | |
| }) | |
| const ui = port => | |
| open('', { | |
| app: { | |
| name: apps.edge, | |
| arguments: [ | |
| '--new-window', | |
| '--no-default-browser-check', | |
| '--allow-insecure-localhost', | |
| '--no-first-run', | |
| '--disable-sync', | |
| '--window-size=1000,300', | |
| `--app=http://127.0.0.1:${port}` | |
| ] | |
| } | |
| }) | |
| // listen for an event | |
| var handler = function () { | |
| console.log('Received kill signal, shutting down gracefully') | |
| server.close(() => { | |
| console.log('Closed out remaining connections') | |
| process.exit(0) | |
| }) | |
| setTimeout(() => { | |
| console.error( | |
| 'Could not close connections in time, forcefully shutting down' | |
| ) | |
| process.exit(1) | |
| }, 10000) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment