JSON Stringify as a Readable Stream with rescursive resolving of any readable streams and Promises.
- 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
npm install --save json-stream-stringify
Convert value to JSON string. Returns a readable stream.
-
value
Any data to convert to JSON. -
replacer
OptionalFunction(key, value)
orArray
.
As a function the returned value replaces the value associated with the key. Details
As an array all other keys are filtered. Details
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"
}
app.get('/api/users', (req, res, next) => JSONStreamStreamify(Users.find().stream()).pipe(res));
- Space option
- Circular dependency detection/handling (infinite loops may occur as it is)
Feel free to contribute.
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).
NodeJS >4.2.2
Copyright (c) 2016 Faleij faleij@gmail.com