js WritableStream

index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="generate">生成</button>
    <button id="abort">终止</button>
    <textarea id="editor" rows="20"></textarea>
    <div id="previewer"></div>
    <script type="module">
        let abort = null;

        async function generate() {
            if (abort) {
                abort = null;
            }
            abort = new AbortController();
			const signal = abort.signal;
            const output = document.getElementById("editor");

            const prompt = "请回答问题:xxx";
            const options = {
                body: `{"prompt": "${prompt}"}`,
                headers: { "Content-Type": "application/json" },
                method: "POST",
                signal: signal,
            };
            const response = await fetch("/chat", options);
            const decoderStream = new TextDecoderStream("utf-8");
            const writer = new WritableStream({
                write(chunk) {
                    output.innerHTML += chunk;
                    output.scrollTop = output.scrollHeight;
                }
            });
            response.body
                .pipeThrough(decoderStream)
                .pipeTo(writer)
                .catch((error) => {
                    console.log(`Something went wrong with the stream: ${error}`);
                });
        }

        const generateElement = document.getElementById("generate");
        generateElement.onclick = () => {
            generate();
        }

        const abortElement = document.getElementById("abort");
        abortElement.onclick = () => {
            if (abort) {
                abort.abort();
            }
        }
    </script>
</body>

</html>
posted @ 2024-08-31 10:15  卓能文  阅读(5)  评论(0编辑  收藏  举报