# stream流式读取内容

<template>
    <div>
        <h1>流式日志显示</h1>
        <pre>{{ log }}</pre>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const log = ref('')

async function fetchLogStream() {
    try {
        const response = await fetch('/proxyApi/log-stream')

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`)
        }

        if (!response.body) {
            throw new Error('Response body is null or undefined.')
        }

        const reader = response.body.getReader()
        const decoder = new TextDecoder('utf-8')
        let result = ''

        while (true) {
            const { done, value } = await reader.read()
            console.group('done: ', done)
            if (done) {
                console.log('Stream finished.')
                break
            }
            // Decode the chunk and append to the result
            const chunk = decoder.decode(value, { stream: true })
            result += chunk
            // Display the current accumulated content
        }
        log.value = result
    } catch (error) {
        console.error('Error fetching log stream:', error)
    }
}

fetchLogStream()
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

当内容读取完毕后,done会变成true

属性名 类型 含义
done boolean 如果为 true,说明流已经读完,没有更多数据
value Uint8Array 或 undefined 当前读取到的数据块(chunk),通常是一个二进制数组