运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

在 Bun 中通过 unix 域套接字进行 fetch

在 Bun 中,fetch() 可以通过 unix 选项,使用 unix 域套接字发送 HTTP 请求。

fetch-unix.ts
const unix = "/var/run/docker.sock";

const response = await fetch("http://localhost/info", { unix });

const body = await response.json();
console.log(body); // { ... }

unix 选项是 unix 域套接字的本地文件路径。fetch() 会通过该套接字发送请求,而不是使用 TCP 连接。也支持 HTTPS:在 URL 中使用 https:// 协议,而不是 http://。

要通过 unix 域套接字发送 POST 请求到 API 端点:

fetch-unix.ts
const response = await fetch("https://hostname/a/path", {
  unix: "/var/run/path/to/unix.sock",
  method: "POST",
  body: JSON.stringify({ message: "Hello from Bun!" }),
  headers: {
    "Content-Type": "application/json",
  },
});

const body = await response.json();