Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

eventsource-encoder

rexxars39MIT1.0.0TypeScript support: included

Encodes events as well-formed EventSource/Server Sent Event (SSE) messages

sse, eventsource, server-sent-events

readme

eventsource-encoder

npm versionnpm bundle sizenpm weekly downloads

An encoding utility package for server-sent events/eventsource.

While the protocol is very simple in theory, there are some common pitfalls - in particular handling of newlines. This package makes it extremely simple to implement a Server-Sent Events endpoint with well-formed messages.

Installation

npm install --save eventsource-encoder

Usage

import {createServer} from 'node:http'
import {encode} from 'eventsource-encoder'

createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
  })

  for (let id = 0; id < 100; id++) {
    res.write(
      encode({
        id,
        event: 'time',
        data: new Date().toISOString(),
      }),
    )
  }
})

Encoding data chunks only

If you want to encode only the data part of the event, you can use the encodeData function:

import {encodeData} from 'eventsource-encoder'

console.log(encodeData('Hello, world!')) // data: Hello, world!\n\n
console.log(encodeData('Hello\nworld!')) // data: Hello\ndata: world!\n\n

Encoding comments

"Comments" in Server-Sent Events are lines that start with a : character. You can use the encodeComment function to encode comments. Note that most EventSource clients have no way of interacting with comments, but they can be useful for debugging or for keeping the connection alive with "heartbeats".

import {encodeComment} from 'eventsource-encoder'

console.log(encodeComment('This is a comment')) // : This is a comment\n
console.log(encodeComment('This\nis\na\nmultiline\ncomment')) // : This\n: is\n: a\n: multiline\n: comment\n

License

MIT © Espen Hovlandsdal

changelog

📓 Changelog

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

1.0.0 (2024-10-09)

Features