Skip to content

Commit cc793b7

Browse files
authored
docs: add EventSource server example (#5321)
Signed-off-by: Will-thom <116388885+Will-thom@users.noreply.github.com>
1 parent f51afa0 commit cc793b7

1 file changed

Lines changed: 50 additions & 3 deletions

File tree

docs/docs/api/EventSource.md

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server
77

88
## Instantiating EventSource
99

10-
Undici exports a EventSource class. You can instantiate the EventSource as
10+
Undici exports an EventSource class. You can instantiate the EventSource as
1111
follows:
1212

1313
```mjs
@@ -19,9 +19,57 @@ eventSource.onmessage = (event) => {
1919
}
2020
```
2121

22+
## Receiving events from a server
23+
24+
EventSource connects to an HTTP endpoint that responds with a `text/event-stream`
25+
content type. The connection stays open and receives events as the server writes
26+
them.
27+
28+
```mjs
29+
import { createServer } from 'node:http'
30+
import { EventSource } from 'undici'
31+
32+
const server = createServer((request, response) => {
33+
response.writeHead(200, {
34+
'content-type': 'text/event-stream',
35+
'cache-control': 'no-cache',
36+
connection: 'keep-alive'
37+
})
38+
39+
response.write('event: ping\n')
40+
response.write('data: connected\n\n')
41+
42+
const interval = setInterval(() => {
43+
response.write(`data: ${Date.now()}\n\n`)
44+
}, 1000)
45+
46+
request.on('close', () => clearInterval(interval))
47+
})
48+
49+
server.listen(3000, () => {
50+
const eventSource = new EventSource('http://localhost:3000')
51+
52+
eventSource.addEventListener('ping', (event) => {
53+
console.log('ping:', event.data)
54+
})
55+
56+
eventSource.onmessage = (event) => {
57+
console.log('message:', event.data)
58+
}
59+
60+
eventSource.onerror = () => {
61+
eventSource.close()
62+
server.close()
63+
}
64+
})
65+
```
66+
67+
The `message` event receives events without an explicit `event:` field. Use
68+
`addEventListener()` to subscribe to named events.
69+
2270
## Using a custom Dispatcher
2371

24-
undici allows you to set your own Dispatcher in the EventSource constructor.
72+
Undici allows you to set your own Dispatcher in the EventSource constructor.
2573

2674
An example which allows you to modify the request headers is:
2775

@@ -38,7 +86,6 @@ class CustomHeaderAgent extends Agent {
3886
const eventSource = new EventSource('http://localhost:3000', {
3987
dispatcher: new CustomHeaderAgent()
4088
})
41-
4289
```
4390

4491
More information about the EventSource API can be found on

0 commit comments

Comments
 (0)