koajs / discussions

KoaJS Discussions
2 stars 2 forks source link

how to set interval within stream #37

Open Tsher opened 8 years ago

Tsher commented 8 years ago

i use coffeescript rewrite this example.

koa= require 'koa'
route= require 'koa-route'
cors = require 'koa-cors'
app= module.exports= koa()

stream= require 'stream'
class Subscription extends stream.Readable
    constructor: (@options)->
        super
        @value = 0
    _read: ->
        @push(String(@value++))

class SSE extends stream.Transform
    _transform: (data, enc, next)->
        @push 'data: ' + data.toString('utf8') + '\n\n'
        next()

app.use cors()
app.use route.get '/sse', ->
    # otherwise node will automatically close this connection in 2 minutes
    @req.setTimeout Number.MAX_VALUE
    @type= 'text/event-stream; charset=utf-8'
    @set 'Cache-Control', 'no-cache'
    @set 'Connection', 'keep-alive'
    body= @body= new SSE
    stream= new Subscription 'some event'
    stream.pipe body

    yield return

if not module.parent then app.listen 3000

run coffee file.coffee then listening on port 3000

curl http://localhost:3000/sse

Original output is printed every 1ms, how could i set it every 1s.