json-stream-stringify
TypeScript icon, indicating that this package has built-in type declarations

1.3.3 • Public • Published

JSON Stream Stringify

NPM version NPM Downloads Dependency Status Build Status Coverage Status License Gratipay

JSON Stringify as a Readable Stream with rescursive resolving of any readable streams and Promises.

Main Features

  • Promises are rescursively resolved and the result is piped through JSONStreamStreamify
  • Streams (ObjectMode) are piped through a transform which pipes the data through JSONStreamStreamify (enabling recursive resolving)
  • Streams (Non-ObjectMode) is stringified and piped
  • Output is streamed optimally with as small chunks as possible
  • Great memory management with reference release post process (When a key and value has been processed the value is dereferenced)
  • Stream pressure handling

Install

npm install --save json-stream-stringify

API

JSONStreamStringify(value[, replacer])

Convert value to JSON string. Returns a readable stream.

  • value Any data to convert to JSON.
  • replacer Optional Function(key, value) or Array.
    As a function the returned value replaces the value associated with the key. Details
    As an array all other keys are filtered. Details

Example Usage

const JSONStreamStreamify = require('json-stream-stringify');

JSONStreamStreamify({
    aPromise: Promise.resolve(Promise.resolve("text")), // Promise may resolve more promises and streams which will be consumed and resolved
    aStream: ReadableObjectStream({a:1}, 'str'), // Stream may write more streams and promises which will be consumed and resolved
    arr: [1, 2, Promise.resolve(3), Promise.resolve([4, 5]), ReadableStream('a', 'b', 'c')],
    date: new Date(2016, 0, 2)
}).pipe(process.stdout);

Output (each line represents a write from JSONStreamStreamify)

{
"aPromise":
"text"
"aStream":
[
{
"a":
1
}
,
"str"
]
"arr":
[
1
,
2
,
3
,
[
4
,
5
]
,
"
a
b
c
"
],
"date":
"2016-01-01T23:00:00.000Z"
}

Practical Example with Express + Mongoose

app.get('/api/users', (req, res, next) => JSONStreamStreamify(Users.find().stream()).pipe(res));

TODO

  • Space option
  • Circular dependency detection/handling (infinite loops may occur as it is)

Feel free to contribute.

Technical Notes

Uses toJSON when available, and JSON.stringify to stringify everything but objects and arrays.
Streams with ObjectMode=true are output as arrays while ObjectMode=false output as a concatinated string (each chunk is piped with transforms).

Requirements

NodeJS >4.2.2

License

MIT

Copyright (c) 2016 Faleij faleij@gmail.com

Readme

Keywords

none

Package Sidebar

Install

npm i json-stream-stringify@1.3.3

Version

1.3.3

License

MIT

Last publish

Collaborators

  • faleij