@haensl/json-transform-stream

A Node.js Transform stream for JSON objects.

Usage no npm install needed!

<script type="module">
  import haenslJsonTransformStream from 'https://cdn.skypack.dev/@haensl/json-transform-stream';
</script>

README

@haensl/json-transform-stream

A Node.js Transform Stream implementation that makes wrapping JSON data easy.

NPM

npm version

CircleCI

Installation

# via npm
npm i --save @haensl/json-transform-stream

# or yarn
yarn add @haensl/json-transform-stream

Usage

const JSONTransform = require('@haensl/json-transform-stream');

const jsonStream = getJSONObjectStreamFromSomewhere()
  .pipe(JSONTransform());

Example: Streaming MongoDB cursors in Koa.

const JSONTransform = require('@haensl/json-transform-stream');

// ...

router.get('/some-resource', async (ctx) => {
  // query your mongodb
  const cursor = await mongo
    .db('some-database')
    .collection('some-colletion')
    .find({
      // query
    });
  // don't forget to set the content type _before_ the first chunk
  ctx.set('Content-Type', 'application/json');
  ctx.status = 200;
  ctx.body = cursor
    .transformStream({
      transform: JSON.stringify // have the mongodb cursor emit JSON stringified chunks
    })
    .pipe(JSONTransform()); // wrap the chunks in an array
});

Example: Safely streaming an array of JSON.

Since sending plain arrays to clients is exploitable, you might want to wrap your array in an object.

const JSONTransform = require('@haensl/json-transform-stream');

// ...

someJSONStream
  .pipe(JSONTransform({
    pre: '{"data":[',
    post: ']}'
  }));

// Result:
// {
//   "data": [
//      // data emitted by someJSONStream
//   ]
// }
}

Synopsis

({
  post = ']',
  pre = '[',
  separator = ','
}) => TransformStream

Parameters

options.post [optional]

Default: ']'

String. Suffix to append to data emitted by this stream.

options.pre [optional]

Default: '['

String. Prefix to prepend to data emitted by this stream.

options.separator [optional]

Default: ','

String. Separator to join data emitted by this stream with.

Returns

TransformStream. A Node.js transform stream.

Changelog

License