Aller au contenu

Utilitaire Streaming ​

L’utilitaire Streaming fournit des méthodes pour envoyer des réponses en flux.

Importation ​

ts
import { Hono } from 'hono'
import { stream, streamText, streamSSE } from 'hono/streaming'

stream() ​

Renvoie une réponse en flux simple sous la forme d’un objet Response.

ts
app.get('/stream', (c) => {
  return stream(c, async (stream) => {
    // Write a process to be executed when aborted.
    stream.onAbort(() => {
      console.log('Aborted!')
    })
    // Write a Uint8Array.
    await stream.write(new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]))
    // Pipe a readable stream.
    await stream.pipe(anotherReadableStream)
  })
})

streamText() ​

Renvoie une réponse en flux avec les en-têtes Content-Type: text/plain, Transfer-Encoding: chunked et X-Content-Type-Options: nosniff.

ts
app.get('/streamText', (c) => {
  return streamText(c, async (stream) => {
    // Write a text with a new line ('\n').
    await stream.writeln('Hello')
    // Wait 1 second.
    await stream.sleep(1000)
    // Write a text without a new line.
    await stream.write(`Hono!`)
  })
})

Attention

Si vous développez une application pour Cloudflare Workers, le streaming peut ne pas fonctionner correctement avec Wrangler. Dans ce cas, ajoutez Identity comme valeur de l’en-tête Content-Encoding.

ts
app.get('/streamText', (c) => {
  c.header('Content-Encoding', 'Identity')
  return streamText(c, async (stream) => {
    // ...
  })
})

streamSSE() ​

Permet d’envoyer facilement des événements Server-Sent Events (SSE) en flux.

ts
const app = new Hono()
let id = 0

app.get('/sse', async (c) => {
  return streamSSE(c, async (stream) => {
    while (!stream.aborted) {
      const message = `It is ${new Date().toISOString()}`
      await stream.writeSSE({
        data: message,
        event: 'time-update',
        id: String(id++),
      })
      await stream.sleep(1000)
    }
  })
})

Gestion des erreurs ​

Le troisième argument de l’utilitaire de streaming est un gestionnaire d’erreurs. Cet argument est facultatif. Si vous ne le spécifiez pas, l’erreur est affichée comme une erreur dans la console.

ts
app.get('/stream', (c) => {
  return stream(
    c,
    async (stream) => {
      // Write a process to be executed when aborted.
      stream.onAbort(() => {
        console.log('Aborted!')
      })
      // Write a Uint8Array.
      await stream.write(
        new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f])
      )
      // Pipe a readable stream.
      await stream.pipe(anotherReadableStream)
    },
    (err, stream) => {
      stream.writeln('An error occurred!')
      console.error(err)
    }
  )
})

Le flux est automatiquement fermé après l’exécution des fonctions de rappel.

Attention

Si la fonction de rappel de l’utilitaire de streaming lève une erreur, l’événement onError de Hono n’est pas déclenché.

onError est un hook qui gère les erreurs avant l’envoi de la réponse et permet de remplacer celle-ci. Cependant, lorsque la fonction de rappel s’exécute, le flux a déjà commencé et la réponse ne peut plus être remplacée.

Publié sous licence MIT.