Skip to content

spb-web/pack-bytes-to-utf8

Repository files navigation

pack-bytes-to-utf8 🔢

CircleCI minified + gzip tree shaking

Install

yarn

yarn add pack-bytes-to-utf8

npm

npm insall pack-bytes-to-utf8

A quick example

import {uint8ArrayToUtf8, utf8ToUint8Array} from 'pack-bytes-to-utf8'

const bytes = new Uint8Array([0xff, 0xff, 0xff, 0xff])

const bytesInString = uint8ArrayToUtf8(bytes)

const parsedBytes = utf8ToUint8Array(bytesInString)

Server-sent events (SSE) example

Server

import {uint8ArrayToUtf8} from 'pack-bytes-to-utf8'

const bytes = new Uint8Array(Buffer.from('0xaa344...64f456', 'hex'))

// Messages in the event stream are separated by a pair of newline 
// characters, so we exclude the line break characters.
//
// Excluded characters will be replaced with double-byte characters.
const excludeCharacters = new Set([0xA, 0xB, 0xC, 0xD, 0xE])

const str = uint8ArrayToUtf8(
  bytes,
  excludeCharacters,
)

app.get('/sse', (req, res) => {
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Connection', 'keep-alive');

  res.write(`data: ${str}\n\n`)
})

Client

import {utf8ToUint8Array} from 'pack-bytes-to-utf8'

const eventSource = new EventSource('http://localhost:3000/sse')

eventSource.addEventListener('message', ({data}) => {
  console.log(utf8ToUint8Array(data))
})

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published