28 lines
942 B
JavaScript
28 lines
942 B
JavaScript
// Minimal streaming SSR server on plain Node http.
|
|||
|
|
// node examples/streaming/server.js
|
||
|
|
// The same ReadableStream plugs into web-standard servers as
|
||
|
|
// `new Response(app.toStream('/'))` — Readable.fromWeb is just the
|
||
|
|
// Node http bridge.
|
||
|
|
|
||
|
|
import { createServer } from 'node:http'
|
||
|
|
import { Readable } from 'node:stream'
|
||
|
|
|
||
|
|
import createApp from './app.js'
|
||
|
|
|
||
|
|
const PORT = process.env.PORT || 8080
|
||
|
|
|
||
|
|
createServer((req, res) => {
|
||
|
|
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
|
||
|
|
res.write('<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>choo streams</title></head>\n')
|
||
|
|
|
||
|
|
const body = Readable.fromWeb(createApp().toStream('/'))
|
||
|
|
body.pipe(res, { end: false })
|
||
|
|
body.on('end', () => res.end('\n</html>'))
|
||
|
|
body.on('error', (err) => {
|
||
|
|
console.error(err)
|
||
|
|
res.destroy()
|
||
|
|
})
|
||
|
|
}).listen(PORT, () => {
|
||
|
|
console.log(`streaming on http://localhost:${PORT} — watch the slow section arrive`)
|
||
|
|
})
|