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!`)
})
})
警告
如果你正在为 Cloudflare Workers 开发应用,流媒体可能无法在 Wrangler 上正常工作。如果是这样,请为 Content-Encoding
标头添加 Identity
。
¥If you are developing an application for Cloudflare Workers, a 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 (true) {
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.
警告
如果流式助手的回调函数抛出错误,则不会触发 Hono 的 onError
事件。
¥If the callback function of the streaming helper throws an error, the onError
event of Hono will not be triggered.
onError
是一个钩子,用于在发送响应之前处理错误并覆盖响应。但是,当执行回调函数时,流已经开始,因此无法覆盖它。
¥onError
is a hook to handle errors before the response is sent and overwrite the response. However, when the callback function is executed, the stream has already started, so it cannot be overwritten.