-
Notifications
You must be signed in to change notification settings - Fork 6.5k
feat: added new learn section with fetch examples #7499
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
90e56ea
feat: added new learn section with fetch examples
benhalverson eac7433
updated code example and added to sidebar
benhalverson d624c89
docs: updated example code
benhalverson 38a1b06
docs: Updated example to use mistral and typo fix
benhalverson 3f7b5b6
docs: spelling
benhalverson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| --- | ||
| title: Node.js Fetch | ||
| layout: learn | ||
| authors: benhalverson, LankyMoose | ||
| --- | ||
|
|
||
| # Using the Fetch API with Undici in Node.js | ||
|
|
||
| ## Introduction | ||
|
|
||
| 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. | ||
|
|
||
| ## Why use Undici? | ||
|
|
||
| [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. | ||
|
|
||
| ```mjs | ||
| import { fetch } from 'undici'; | ||
|
|
||
| async function main() { | ||
| const response = await fetch('https://jsonplaceholder.typicode.com/posts'); | ||
| const data = await response.json(); | ||
| console.log(data); | ||
| } | ||
|
|
||
| main().catch(console.error); | ||
| ``` | ||
|
|
||
| ## Customizing the Fetch API with Undici | ||
|
|
||
| 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: | ||
|
|
||
| ```mjs | ||
| import { Pool } from 'undici'; | ||
|
|
||
| const ollamaPool = new Pool('http://localhost:11434', { | ||
| connections: 10, | ||
| }); | ||
|
|
||
| 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: 'deepseek-r1:8b' }), | ||
| }); | ||
|
|
||
| if (statusCode !== 200) { | ||
| 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(); | ||
| } | ||
| ``` | ||
|
|
||
| ## Streaming Responses with Undici | ||
|
|
||
| ```mjs | ||
| import { stream } from 'undici'; | ||
| import { Writable } from 'stream'; | ||
|
|
||
| async function fetchGitHubRepos() { | ||
| const url = 'https://api.github.com/users/nodejs/repos'; | ||
|
|
||
| const { statusCode } = await stream( | ||
| url, | ||
| { | ||
| method: 'GET', | ||
| headers: { | ||
| 'User-Agent': 'undici-stream-example', | ||
| Accept: 'application/json', | ||
| }, | ||
| }, | ||
| () => { | ||
| let buffer = ''; | ||
|
|
||
| return new Writable({ | ||
| write(chunk, encoding, callback) { | ||
| buffer += chunk.toString(); | ||
|
|
||
| try { | ||
| const json = JSON.parse(buffer); | ||
| console.log( | ||
| 'Repository Names:', | ||
| json.map(repo => repo.name) | ||
| ); | ||
| buffer = ''; | ||
| } catch (error) { | ||
| console.error('Error parsing JSON:', error); | ||
| } | ||
|
|
||
| callback(); | ||
| }, | ||
| final(callback) { | ||
| console.log('Stream processing completed.'); | ||
| callback(); | ||
| }, | ||
| }); | ||
| } | ||
| ); | ||
|
|
||
| console.log(`Response status: ${statusCode}`); | ||
| } | ||
|
|
||
| fetchGitHubRepos().catch(console.error); | ||
| ``` | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.