Home

Awesome

it-length-prefixed

codecov CI

Streaming length prefixed buffers with async iterables

About

<!-- !IMPORTANT! Everything in this README between "# About" and "# Install" is automatically generated and will be overwritten the next time the doc generator is run. To make changes to this section, please update the @packageDocumentation section of src/index.js or src/index.ts To experiment with formatting, please run "npm run docs" from the root of this repo and examine the changes made. -->

Encode/decode streams of bytes with length-prefixes.

Example

import { pipe } from 'it-pipe'
import * as lp from 'it-length-prefixed'

const encoded = []

// encode
await pipe(
  [uint8ArrayFromString('hello world')],
  (source) => lp.encode(source),
  async source => {
    for await (const chunk of source) {
      encoded.push(chunk.slice()) // (.slice converts Uint8ArrayList to Uint8Array)
    }
  }
)

console.log(encoded)
// => [Buffer <0b 68 65 6c 6c 6f 20 77 6f 72 6c 64>]

const decoded = []

// decode
await pipe(
  encoded, // e.g. from above
  (source) => lp.decode(source),
  async source => {
    for await (const chunk of source) {
      decoded.push(chunk.slice()) // (.slice converts Uint8ArrayList to Uint8Array)
    }
  }
)

console.log(decoded)
// => [Buffer <68 65 6c 6c 6f 20 77 6f 72 6c 64>]

API

import {
  encode, decode
} from 'it-length-prefixed'

import {
  encode
} from 'it-length-prefixed/encode'

import {
  decode,
  MAX_LENGTH_LENGTH,
  MAX_DATA_LENGTH
} from 'it-length-prefixed/decode'

encode(source, [opts])

Returns Generator or AsyncGenerator that yields Uint8ArrayList objects. All messages will be prefixed with a length, determined by the lengthEncoder function.

encode.single(chunk, [opts])

Returns a Uint8ArrayList containing the encoded chunk.

decode(source, [opts])

Returns Generator or AsyncGenerator that yields Uint8ArrayList objects.

decode.fromReader(reader, [opts])

Behaves like decode except it only reads the exact number of bytes needed for each message in reader.

Returns Generator or AsyncGenerator that yields Uint8ArrayList objects.

API Docs

License

Licensed under either of

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.