Skip to content

Commit 3cddbc2

Browse files
committed
Improve performance for large messages across many chunks
1 parent 82d38b0 commit 3cddbc2

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

lib/eventsource.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,8 @@ function EventSource (url, eventSourceInitDict) {
174174
// Source/WebCore/page/EventSource.cpp
175175
var isFirst = true
176176
var buf
177+
var startingPos = 0
178+
var startingFieldLength = -1
177179
res.on('data', function (chunk) {
178180
buf = buf ? Buffer.concat([buf, chunk]) : chunk
179181
if (isFirst && hasBom(buf)) {
@@ -193,10 +195,10 @@ function EventSource (url, eventSourceInitDict) {
193195
}
194196

195197
var lineLength = -1
196-
var fieldLength = -1
198+
var fieldLength = startingFieldLength
197199
var c
198200

199-
for (var i = pos; lineLength < 0 && i < length; ++i) {
201+
for (var i = startingPos; lineLength < 0 && i < length; ++i) {
200202
c = buf[i]
201203
if (c === colon) {
202204
if (fieldLength < 0) {
@@ -211,7 +213,12 @@ function EventSource (url, eventSourceInitDict) {
211213
}
212214

213215
if (lineLength < 0) {
216+
startingPos = length - pos
217+
startingFieldLength = fieldLength
214218
break
219+
} else {
220+
startingPos = 0
221+
startingFieldLength = -1
215222
}
216223

217224
parseEventStreamLine(buf, pos, fieldLength, lineLength)

test/eventsource_test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,26 @@ describe('Parser', function () {
466466
}
467467
})
468468
})
469+
470+
it('parses a relatively huge message across many chunks efficiently', function (done) {
471+
this.timeout(1000)
472+
473+
createServer(function (err, server) {
474+
if (err) return done(err)
475+
476+
var longMessageContent = new Array(100000).join('a')
477+
var longMessage = 'data: ' + longMessageContent + '\n\n'
478+
var longMessageChunks = longMessage.match(/[\s\S]{1,10}/g) // Split the message into chunks of 10 characters
479+
server.on('request', writeEvents(longMessageChunks))
480+
481+
var es = new EventSource(server.url)
482+
483+
es.onmessage = function (m) {
484+
assert.equal(longMessageContent, m.data)
485+
server.close(done)
486+
}
487+
})
488+
})
469489
})
470490

471491
describe('HTTP Request', function () {

0 commit comments

Comments
 (0)