Skip to content

Commit d6b36a2

Browse files
committed
Error objects structure synchronized. Added usage to README.md
1 parent a64e71b commit d6b36a2

File tree

2 files changed

+36
-12
lines changed

2 files changed

+36
-12
lines changed

README.md

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,37 @@
1-
# EventSource implementation for Node.js
1+
EventSource implementation for Node.js
2+
===
23

34
This library implements [EventSource (Server-Sent Events client)](https://www.w3.org/TR/eventsource/) for Node.js.
45

5-
**There're no tests for this library**
6+
**There're no tests for this library**
7+
8+
Usage
9+
-----
10+
11+
```javascript
12+
import EventSource from "../src/eventsource"
13+
14+
// HTTP and HTTPS URLs are supported
15+
const es = new EventSource("http://localhost/sse", {
16+
// Reconnect timeout in milliseconds
17+
reconnectTimeout: 1000,
18+
// Custom headers
19+
headers: {
20+
"X-API-Token": "1a414f28633194f1450af2661001df8f"
21+
}
22+
})
23+
24+
es.on("message", (event) => {
25+
console.log("Got event", event)
26+
})
27+
28+
es.on("error", (err) => {
29+
console.log("Error:", err)
30+
})
31+
32+
es.on("connecting", () => {
33+
console.log("Connecting")
34+
})
35+
36+
// Use `es.close()` to close EventSource
37+
```

src/eventsource.ts

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ class EventSource extends EventEmitter {
9191
this.emit("error", err)
9292
})
9393
this._req.on("close", () => {
94-
this.emit("error", { msg: "connection lost" })
94+
this.emit("error", { reason: "connection lost" })
9595
this._req.removeAllListeners()
9696
this._readyState = ReadyState.CLOSED
9797
this._reconnect()
@@ -111,19 +111,11 @@ class EventSource extends EventEmitter {
111111

112112
private _handleResponse(res: ClientResponse) {
113113
if (res.statusCode > 399) {
114-
this.emit("error", { status: res.statusCode })
115-
this._reconnect()
114+
this.emit("error", { status: res.statusCode, reason: res.statusMessage })
116115
return
117116
}
118117
console.log("Connected")
119118
this._readyState = ReadyState.OPEN
120-
/*
121-
res.on("close", () => {
122-
this.emit("error", { msg: "connection lost" })
123-
this._readyState = ReadyState.CLOSED
124-
this._reconnect()
125-
})
126-
*/
127119
const parser = new EventStreamParser()
128120
res.pipe(parser)
129121
parser.on("data", (event) => {

0 commit comments

Comments
 (0)