讲师中心 微信公众号
AI工具推荐 视频效率加速

与发bun活着重新加载html

风枫君_9942

风枫君_9942

发布时间:2025-02-08 08:10:10

|

305人浏览过

|

来源于php中文网

原创

this article demonstrates how to create a simple live reload mechanism for html content using bun's built-in http server and server-sent events (sse). this allows the browser to automatically refresh whenever the server-side code changes, eliminating the need for manual refreshes.

与发bun活着重新加载html

The Problem: Bun's bun -hot command reloads the server on code changes, but the browser doesn't automatically refresh, requiring manual intervention.

The Solution (SSE): This approach leverages SSE, a unidirectional communication method (server to browser), avoiding the overhead of a full WebSocket connection. When the server restarts (due to code changes), it sends an SSE message to the browser, triggering a page reload.

Implementation Steps:

立即学习“前端免费学习笔记(深入)”;

  1. SSE Endpoint: Create a /__bun_live_reload endpoint that returns a ReadableStream with a text/event-stream content type. This stream will send the reload signal.

    Add Typescript Best Practices
    Add Typescript Best Practices

    在 CLAUDE.md 中配置 TypeScript 最佳实践和代码风格规则

    下载
  2. Injecting the Client-Side Script: A JavaScript snippet is injected into every HTML response. This script uses the EventSource API to listen for messages from the /__bun_live_reload endpoint. Upon receiving a message, location.reload() refreshes the page.

  3. Handling Server Reloads: Bun's hot reload mechanism is utilized. A global variable (globalThis.client) stores the ReadableStreamDefaultController. When the server restarts, a message ("data:\n\n") is sent via globalThis.client?.enqueue() to the browser through the SSE stream.

  4. withHtmlLiveReload Wrapper: A function wraps the original fetch handler. It intercepts responses, injects the client-side script, and handles the SSE endpoint.

Code (bun-html-live-reload.ts):

<code class="typescript">declare global {
  var client: ReadableStreamDefaultController | undefined;
}

type Fetch = (req: Request) => Promise<Response>;

const liveReloadScript = `
  new EventSource("/__bun_live_reload").onmessage = () => {
    location.reload();
  };
`;

export function withHtmlLiveReload(handler: Fetch): Fetch {
  return async (req) => {
    if (new URL(req.url).pathname === "/__bun_live_reload") {
      const stream = new ReadableStream({
        start(controller) {
          globalThis.client = controller;
        },
      });
      return new Response(stream, {
        headers: {
          "Content-Type": "text/event-stream",
          "Cache-Control": "no-cache",
        },
      });
    }

    const response = await handler(req);
    const htmlText = await response.text();
    const newHtmlText = htmlText + liveReloadScript;
    return new Response(newHtmlText, { headers: response.headers });
  };
}

// Example usage in your server.ts:
import { withHtmlLiveReload } from "./bun-html-live-reload";

bun.serve({
  fetch: withHtmlLiveReload(async (req) => {
    return new Response("<h1>Hello, world!</h1>", {
      headers: { "Content-Type": "text/html" },
    });
  }),
});

// In your server.ts, make sure to add this to trigger the reload:
globalThis.client?.enqueue("data:\n\n");</code>

By using this withHtmlLiveReload function, you can easily add live reload functionality to your Bun server-rendered websites. Remember to run your server with bun -hot.

热门AI工具

更多
AionClaw
AionClaw Hot

AionClaw是一款面向办公、创作和编程任务的AI桌面智能体。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

讯飞绘文

讯飞绘文是一款由科大讯飞推出的一站式 AIGC 内容运营平台。

二狗PPT
二狗PPT Hot

一款AI演示文稿工具,主要用于专为中式职场打造的AI PPT生成工具,适合需要提升相关任务效率的用户。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

PixPix
PixPix Hot

PixPix是一款面向电商视觉生产的AI商品图生成工具。

UpDream
UpDream Hot

一款AI视频创作工具,主要用于哔哩哔哩推出的自研AI视频创作工具,适合需要提升相关任务效率的用户。

Atoms
Atoms Hot

Atoms是一款AI智能体工具,第一支自动构建真实业务的 AI 团队。

相关专题

更多
function是什么
function是什么

function是函数的意思,是一段具有特定功能的可重复使用的代码块,是程序的基本组成单元之一,可以接受输入参数,执行特定的操作,并返回结果。本专题为大家提供function是什么的相关的文章、下载、课程内容,供大家免费下载体验。

2920

2023.08.04

js函数function用法
js函数function用法

js函数function用法有:1、声明函数;2、调用函数;3、函数参数;4、函数返回值;5、匿名函数;6、函数作为参数;7、函数作用域;8、递归函数。本专题提供js函数function用法的相关文章内容,大家可以免费阅读。

494

2023.10.07

location.assign
location.assign

在前端开发中,我们经常需要使用JavaScript来控制页面的跳转和数据的传递。location.assign就是JavaScript中常用的一个跳转方法。通过location.assign,我们可以在当前窗口或者iframe中加载一个新的URL地址,并且可以保存旧页面的历史记录。php中文网为大家带来了location.assign的相关知识、以及相关文章等内容,供大家免费下载使用。

2542

2023.06.27

http500解决方法
http500解决方法

http500解决方法有检查服务器日志、检查代码错误、检查服务器配置、检查文件和目录权限、检查资源不足、更新软件版本、重启服务器或寻求专业帮助等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

3283

2023.11.09

http请求415错误怎么解决
http请求415错误怎么解决

解决方法:1、检查请求头中的Content-Type;2、检查请求体中的数据格式;3、使用适当的编码格式;4、使用适当的请求方法;5、检查服务器端的支持情况。更多http请求415错误怎么解决的相关内容,可以阅读下面的文章。

854

2023.11.14

HTTP 503错误解决方法
HTTP 503错误解决方法

HTTP 503错误表示服务器暂时无法处理请求。想了解更多http错误代码的相关内容,可以阅读本专题下面的文章。

6366

2024.03.12

http与https有哪些区别
http与https有哪些区别

http与https的区别:1、协议安全性;2、连接方式;3、证书管理;4、连接状态;5、端口号;6、资源消耗;7、兼容性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

5390

2024.08.16

Go 语言 HTTP 编程与中间件开发教程合集
Go 语言 HTTP 编程与中间件开发教程合集

全面讲解 Go 语言 HTTP 编程的核心知识,涵盖 net/http 标准库的 Server/Handler/HandlerFunc 体系、DefaultServeMux 路由注册与自定义路由器、Request / ResponseWriter 请求响应处理、中间件(Middleware)链式设计模式与常见中间件(日志/CORS/认证/限流)开发、http.Client 的超时配置与连接池管理、Cookie / Session 处理、

461

2026.05.08

PixTV官网入口地址合集
PixTV官网入口地址合集

本专题汇总了 PixTV AI 一站式视频创作平台的官方入口与使用教程。无需下载软件,浏览器直接访问即可使用。平台将剧本、图像、视频、声音与剪辑整合在“无限画布”中,接入 GPT Image 2.5、Seedance 2.5 等头部模型。本专题整理了从新建画布、角色锚定、分镜拆分到视频生成与导出的完整操作指南,助你快速上手 AI 短剧与漫剧创作。

20

2026.10.10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WebStorm 官方调试文档
WebStorm 官方调试文档

共0课时 | 0人学习

TypeScript 教程
TypeScript 教程

共19课时 | 6.6万人学习

TypeScript——十天技能课堂
TypeScript——十天技能课堂

共21课时 | 1.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn