|
| 1 | +--- |
| 2 | +title: Node.js Fetch |
| 3 | +layout: learn |
| 4 | +authors: benhalverson, LankyMoose |
| 5 | +--- |
| 6 | + |
| 7 | +# Using the Fetch API with Undici in Node.js |
| 8 | + |
| 9 | +## Introduction |
| 10 | + |
| 11 | +In this guide, we will learn how to use the Fetch API with Undici in Node.js. The Fetch API is a modern interface that allows you to make HTTP requests in the browser. It is similar to the XMLHttpRequest object, but with a more powerful and flexible feature set. Undici is a high-performance HTTP/1.1 client that is designed to be used with Node.js. It is built on top of the HTTP/1.1 parser from Node.js core, and it provides a simple and efficient API for making HTTP requests. |
| 12 | + |
| 13 | +## Why use Undici? |
| 14 | + |
| 15 | +[Undici](https://undici.nodejs.org) is a high-performance HTTP client for Node.js. While Node.js 18+ ships with a built-in Fetch API. |
| 16 | + |
| 17 | +```mjs |
| 18 | +import { fetch } from 'undici'; |
| 19 | + |
| 20 | +async function main() { |
| 21 | + const response = await fetch('https://jsonplaceholder.typicode.com/posts'); |
| 22 | + const data = await response.json(); |
| 23 | + console.log(data); |
| 24 | +} |
| 25 | + |
| 26 | +main().catch(console.error); |
| 27 | +``` |
| 28 | + |
| 29 | +## Customizing the Fetch API with Undici |
| 30 | + |
| 31 | +Undici allows you to customize the Fetch API by providing options to the `fetch` function. For example, you can set custom headers, set the request method, and set the request body. Here is an example of how you can customize the Fetch API with Undici: |
| 32 | + |
| 33 | +```mjs |
| 34 | +import { Pool } from 'undici'; |
| 35 | + |
| 36 | +const ollamaPool = new Pool('http://localhost:11434', { |
| 37 | + connections: 10, |
| 38 | +}); |
| 39 | + |
| 40 | +async function streamOllamaCompletion(prompt) { |
| 41 | + const { statusCode, body } = await ollamaPool.request({ |
| 42 | + path: '/api/generate', |
| 43 | + method: 'POST', |
| 44 | + headers: { |
| 45 | + 'Content-Type': 'application/json', |
| 46 | + }, |
| 47 | + body: JSON.stringify({ prompt, model: 'deepseek-r1:8b' }), |
| 48 | + }); |
| 49 | + |
| 50 | + if (statusCode !== 200) { |
| 51 | + throw new Error(`Ollama request failed with status ${statusCode}`); |
| 52 | + } |
| 53 | + |
| 54 | + let partial = ''; |
| 55 | + |
| 56 | + const decoder = new TextDecoder(); |
| 57 | + for await (const chunk of body) { |
| 58 | + partial += decoder.decode(chunk, { stream: true }); |
| 59 | + console.log(partial); |
| 60 | + } |
| 61 | + |
| 62 | + console.log('Streaming complete.'); |
| 63 | +} |
| 64 | + |
| 65 | +try { |
| 66 | + await streamOllamaCompletion('What is recursion?'); |
| 67 | +} catch (error) { |
| 68 | + console.error('Error calling Ollama:', error); |
| 69 | +} finally { |
| 70 | + console.log('Closing Ollama pool.'); |
| 71 | + ollamaPool.close(); |
| 72 | +} |
| 73 | +``` |
| 74 | + |
| 75 | +## Streaming Responses with Undici |
| 76 | + |
| 77 | +```mjs |
| 78 | +import { stream } from 'undici'; |
| 79 | +import { Writable } from 'stream'; |
| 80 | + |
| 81 | +async function fetchGitHubRepos() { |
| 82 | + const url = 'https://api.github.com/users/nodejs/repos'; |
| 83 | + |
| 84 | + const { statusCode } = await stream( |
| 85 | + url, |
| 86 | + { |
| 87 | + method: 'GET', |
| 88 | + headers: { |
| 89 | + 'User-Agent': 'undici-stream-example', |
| 90 | + Accept: 'application/json', |
| 91 | + }, |
| 92 | + }, |
| 93 | + () => { |
| 94 | + let buffer = ''; |
| 95 | + |
| 96 | + return new Writable({ |
| 97 | + write(chunk, encoding, callback) { |
| 98 | + buffer += chunk.toString(); |
| 99 | + |
| 100 | + try { |
| 101 | + const json = JSON.parse(buffer); |
| 102 | + console.log( |
| 103 | + 'Repository Names:', |
| 104 | + json.map(repo => repo.name) |
| 105 | + ); |
| 106 | + buffer = ''; |
| 107 | + } catch (error) { |
| 108 | + console.error('Error parsing JSON:', error); |
| 109 | + } |
| 110 | + |
| 111 | + callback(); |
| 112 | + }, |
| 113 | + final(callback) { |
| 114 | + console.log('Stream processing completed.'); |
| 115 | + callback(); |
| 116 | + }, |
| 117 | + }); |
| 118 | + } |
| 119 | + ); |
| 120 | + |
| 121 | + console.log(`Response status: ${statusCode}`); |
| 122 | +} |
| 123 | + |
| 124 | +fetchGitHubRepos().catch(console.error); |
| 125 | +``` |
0 commit comments