Skip to content

Commit b391c9b

Browse files
authored
parse JSON at the end of the stream and use status code from the response
Signed-off-by: NunoMCP <NunoMCP@users.noreply.github.com>
1 parent 9fbb9f6 commit b391c9b

File tree

1 file changed

+6
-12
lines changed
  • apps/site/pages/en/learn/getting-started

1 file changed

+6
-12
lines changed

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

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -134,13 +134,12 @@ try {
134134

135135
```js
136136
import { Writable } from 'stream';
137-
138137
import { stream } from 'undici';
139138

140139
async function fetchGitHubRepos() {
141140
const url = 'https://api.github.com/users/nodejs/repos';
142141

143-
const { statusCode } = await stream(
142+
await stream(
144143
url,
145144
{
146145
method: 'GET',
@@ -149,35 +148,30 @@ async function fetchGitHubRepos() {
149148
Accept: 'application/json',
150149
},
151150
},
152-
() => {
151+
(res) => {
153152
let buffer = '';
154153

155154
return new Writable({
156155
write(chunk, encoding, callback) {
157156
buffer += chunk.toString();
158-
157+
callback();
158+
},
159+
final(callback) {
159160
try {
160161
const json = JSON.parse(buffer);
161162
console.log(
162163
'Repository Names:',
163164
json.map(repo => repo.name)
164165
);
165-
buffer = '';
166166
} catch (error) {
167167
console.error('Error parsing JSON:', error);
168168
}
169-
170-
callback();
171-
},
172-
final(callback) {
173-
console.log('Stream processing completed.');
169+
console.log(`Response status: ${res.statusCode}`);
174170
callback();
175171
},
176172
});
177173
}
178174
);
179-
180-
console.log(`Response status: ${statusCode}`);
181175
}
182176

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

0 commit comments

Comments
 (0)