M
M
monochromer2022-03-17 16:51:53
Node.js
monochromer, 2022-03-17 16:51:53

How to render HTML via node.js streams with Safari support?

I render html through streams. The problem with Safari is that it doesn't output in chunks, but rather buffers and then outputs everything at once.

const { createServer } = require('node:http')
const { setTimeout: delay } = require('node:timers/promises')

createServer(requestHandler)
  .listen(process.env.PORT || 3000, () => {
    console.log(`Server is running on http://localhost:3000`)
  })

async function requestHandler(request, response) {
  const items = ['a', 'b', 'c', 'd', 'e', 'f']

  response.writeHead(200, {
    'content-type': 'text/html; charset=utf-8'
  })

  response.write(`
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Stream Example</title>
    </head>
    <body>
  `)

  for await (const item of items) {
    response.write(`
      <div>${item}</div>
    `)
    await delay(1000)
  }

  response.end(`
    </body>
    </html>
  `)
}

repl.it

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question