sse-stream

2020-02-12

sse-stream

expose html5 server sent events (sse) as a writable stream

sse-stream

Expose HTML5 Server Sent Eventsas an installable appliance on Node.JS httpservers; connections are emitted as Writable streams.

var http = require('http')
  , fs = require('fs')
  , through = require('through')
  , sse = require('sse-stream')('/sse')
  , serv

module.exports = serv = http.createServer(function(req, resp) {
  resp.setHeader('content-type', 'text/html')
  resp.end('<html><body><script type="text/javascript">('+js+')()</script></body></html>')
})

sse.install(serv)

sse.on('connection', function(client) {
  fs.createReadStream('/usr/share/dict/words')
    .pipe(through(function(buf) { this.emit('data', buf.toString()) }))
    .pipe(client)
})

// client-side code:
function js() {
  var es = new EventSource('/sse')
    , pre = document.createElement('pre')
    , closed = false

  document.body.appendChild(pre)

  es.onmessage = function(ev) {
    if(closed) return

    pre.appendChild(document.createTextNode(ev.data))

    window.scrollTo(0, pre.clientHeight)
  }

  es.addEventListener('end', function() {
    es.close()
    closed = true
  }, true)

  es.onerror = function(e) {
    closed = true
  }
}

API

sse = require('sse-stream')(path | options)

Create a SSE server that emits connectionevents on new, successful eventstream connections.

The argument may either be a string pathto listen on (defaults to /sse/) or an object:

{ path: '/listen/on/this/path'
, keepalive: 1000 }

keepalivedetermines the interval time in ms that keepalives will be sent to all connected clients.

sse.on('connection', function(client))

clientis a writable stream representing a client connection (request response pair).

Of note, all data sent through this connection will be stringified before sending due to the event stream spec.

client.retry(integer ms)

Send a "retry" message that lets the client know how many MS to wait until retrying a connection that ended.

license

MIT

以上是 sse-stream 的使用教程帮助文档。


上一篇:@pollyjs/adapter
下一篇:lambci
相关教程
关注微信

扫码加入 JavaScript 社区

相关文章

首次访问,需要验证
微信扫码,关注即可
(仅需验证一次)

欢迎加入 JavaScript 社区

号内回复关键字:

回到顶部