Skip to content

haensl/json-transform-stream

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

@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

About

A Node.js Transform stream for JSON objects.

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published