Appearance
流式助手
🌐 Streaming Helper
Streaming Helper 提供用于流式响应的方法。
🌐 The Streaming Helper provides methods for streaming responses.
导入
🌐 Import
ts
import { Hono } from 'hono'
import { stream, streamText, streamSSE } from 'hono/streaming'stream()
它返回一个简单的流式响应,作为 Response 对象。
🌐 It returns a simple streaming response as Response object.
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()
它返回一个带有 Content-Type: text/plain、Transfer-Encoding: chunked 和 X-Content-Type-Options: nosniff 头的流式响应。
🌐 It returns a streaming response with Content-Type: text/plain, Transfer-Encoding: chunked, and X-Content-Type-Options: nosniff headers.
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!`)
})
})WARNING
如果你正在为 Cloudflare Workers 开发应用,流式传输在 Wrangler 上可能效果不佳。如果是这样,请为 Content-Encoding 头添加 Identity。
🌐 If you are developing an application for Cloudflare Workers, streaming may not work well on Wrangler. If so, add Identity for Content-Encoding header.
ts
app.get('/streamText', (c) => {
c.header('Content-Encoding', 'Identity')
return streamText(c, async (stream) => {
// ...
})
})streamSSE()
它允许你无缝地流式传输服务器发送事件 (SSE)。
🌐 It allows you to stream Server-Sent Events (SSE) seamlessly.
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)
}
})
})错误处理
🌐 Error Handling
流式助手的第三个参数是错误处理程序。此参数是可选的,如果你不指定它,错误将作为控制台错误输出。
🌐 The third argument of the streaming helper is an error handler. This argument is optional, if you don't specify it, the error will be output as a console error.
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)
}
)
})执行回调后,流将自动关闭。
🌐 The stream will be automatically closed after the callbacks are executed.
WARNING
如果流式辅助的回调函数抛出错误,Hono 的 onError 事件将不会被触发。
🌐 If the callback function of the streaming helper throws an error, the onError event of Hono will not be triggered.
onError 是一个在响应发送前处理错误并覆盖响应的钩子。然而,当回调函数执行时,流已经开始,所以无法覆盖。