Skip to content

Commit ca6a3dd

Browse files
NunoMCPavivkeller
andauthored
docs(learn): correct the example code for Streaming Responses with Undici (#8327)
* parse JSON at the end of the stream and use status code from the response Signed-off-by: NunoMCP <[email protected]> * Add log Signed-off-by: NunoMCP <[email protected]> * Update apps/site/pages/en/learn/getting-started/fetch.md Co-authored-by: Aviv Keller <[email protected]> Signed-off-by: NunoMCP <[email protected]> * make prettier happy Signed-off-by: NunoMCP <[email protected]> * trigger build --------- Signed-off-by: NunoMCP <[email protected]> Co-authored-by: Aviv Keller <[email protected]>
1 parent 835090e commit ca6a3dd

File tree

1 file changed

+7
-11
lines changed
  • apps/site/pages/en/learn/getting-started

1 file changed

+7
-11
lines changed

apps/site/pages/en/learn/getting-started/fetch.md

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -135,14 +135,14 @@ try {
135135
[Streams](https://nodejs.org/docs/v22.14.0/api/stream.html#stream) is a feature in Node.js that allows you to read and write chunks of data.
136136

137137
```js
138-
import { Writable } from 'stream';
138+
import { Writable } from 'node:stream';
139139

140140
import { stream } from 'undici';
141141

142142
async function fetchGitHubRepos() {
143143
const url = 'https://api.github.com/users/nodejs/repos';
144144

145-
const { statusCode } = await stream(
145+
await stream(
146146
url,
147147
{
148148
method: 'GET',
@@ -151,35 +151,31 @@ async function fetchGitHubRepos() {
151151
Accept: 'application/json',
152152
},
153153
},
154-
() => {
154+
res => {
155155
let buffer = '';
156156

157157
return new Writable({
158158
write(chunk, encoding, callback) {
159159
buffer += chunk.toString();
160-
160+
callback();
161+
},
162+
final(callback) {
161163
try {
162164
const json = JSON.parse(buffer);
163165
console.log(
164166
'Repository Names:',
165167
json.map(repo => repo.name)
166168
);
167-
buffer = '';
168169
} catch (error) {
169170
console.error('Error parsing JSON:', error);
170171
}
171-
172-
callback();
173-
},
174-
final(callback) {
175172
console.log('Stream processing completed.');
173+
console.log(`Response status: ${res.statusCode}`);
176174
callback();
177175
},
178176
});
179177
}
180178
);
181-
182-
console.log(`Response status: ${statusCode}`);
183179
}
184180

185181
fetchGitHubRepos().catch(console.error);

0 commit comments

Comments
 (0)