Skip to main content
在 Bun 中,fetch()unix 选项允许你通过 unix 域套接字 发送 HTTP 请求。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79fetch-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 网络连接。通过在 URL 中使用 https:// 协议代替 http://,也支持 https 要通过 unix 域套接字发送 POST 请求到 API 端点:
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79fetch-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();