在 Bun 中,fetch() 的 unix 选项允许你通过 unix 域套接字 发送 HTTP 请求。
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 域套接字向 API 端点发送 POST 请求:
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();