Undici 是一个 HTTP 客户端库,为 Node.js 中的 fetch API 提供支持。它从零开始编写,不依赖 Node.js 内置 HTTP 客户端。它包含许多特性,使其成为高性能应用的不错选择。
有关 Undici 对规范的遵循情况,请参阅 Undici 文档。
async function main() { // 与浏览器 fetch API 一样,默认方法是 GET const response = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await response.json(); console.log(data); // 返回内容类似: // { // userId: 1, // id: 1, // title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', // body: 'quia et suscipit\n' + // 'suscipit recusandae consequuntur expedita et cum\n' + // 'reprehenderit molestiae ut ut quas totam\n' + // 'nostrum rerum est autem sunt rem eveniet architecto' // } } main().catch(console.error);
// 从客户端发送到服务器的数据 const body = { title: 'foo', body: 'bar', userId: 1, }; async function main() { const response = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'User-Agent': 'undici-stream-example', 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); const data = await response.json(); console.log(data); // 返回内容类似: // { title: 'foo', body: 'bar', userId: 1, id: 101 } } main().catch(console.error);
Undici 允许你通过向 fetch 函数提供选项来自定义 Fetch API。例如,你可以设置自定义请求头、请求方法和请求体。下面是一个使用 Undici 自定义 Fetch API 的示例:
fetch 函数接受两个参数:要获取的 URL 和一个选项对象。该选项对象是一个请求选项对象,可用于自定义请求。该函数返回一个 Promise,其解析值为一个 Response 对象。
在下面的示例中,我们向 Ollama API 发送一个带 JSON 载荷的 POST 请求。Ollama 是一个 CLI 工具,可让你在本地机器上运行 LLM(大型语言模型)。你可以在这里下载它。
ollama run mistral
这会下载 mistral 模型并在本地机器上运行它。
使用连接池可以复用与同一服务器的连接,从而提升性能。下面是一个如何在 Undici 中使用连接池的示例:
import { Pool } from 'undici'; const ollamaPool = new Pool('http://localhost:11434', { connections: 10, }); /** * 使用 Ollama API 流式输出提示词的补全结果。 * @param {string} prompt - 需要补全的提示词。 * @link https://github.com/ollama/ollama/blob/main/docs/api.md **/ async function streamOllamaCompletion(prompt) { const { statusCode, body } = await ollamaPool.request({ path: '/api/generate', method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ prompt, model: 'mistral' }), }); // 你可以在这里了解 HTTP 状态码:https://developer.mozilla.org/en-US/docs/Web/HTTP/Status // 200 表示请求成功。 if (statusCode !== 200) { // 必须消费响应体:https://undici.nodejs.org/#/?id=garbage-collection await body.dump(); throw new Error(`Ollama request failed with status ${statusCode}`); } let partial = ''; const decoder = new TextDecoder(); for await (const chunk of body) { partial += decoder.decode(chunk, { stream: true }); console.log(partial); } console.log('Streaming complete.'); } try { await streamOllamaCompletion('What is recursion?'); } catch (error) { console.error('Error calling Ollama:', error); } finally { console.log('Closing Ollama pool.'); ollamaPool.close(); }
Streams 是 Node.js 的一项特性,让你可以读取和写入数据块。
import { Writable } from 'node:stream'; import { stream } from 'undici'; async function fetchGitHubRepos() { const url = 'https://api.github.com/users/nodejs/repos'; await stream( url, { method: 'GET', headers: { 'User-Agent': 'undici-stream-example', Accept: 'application/json', }, }, res => { let buffer = ''; return new Writable({ write(chunk, encoding, callback) { buffer += chunk.toString(); callback(); }, final(callback) { try { const json = JSON.parse(buffer); console.log( 'Repository Names:', json.map(repo => repo.name) ); } catch (error) { console.error('Error parsing JSON:', error); } console.log('Stream processing completed.'); console.log(`Response status: ${res.statusCode}`); callback(); }, }); } ); } fetchGitHubRepos().catch(console.error);