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 @   卓能文  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示