| 1 | 'use strict'
|
|---|
| 2 |
|
|---|
| 3 | const promise = require('./promise')
|
|---|
| 4 | const streamify = require('./streamify')
|
|---|
| 5 |
|
|---|
| 6 | module.exports = stringify
|
|---|
| 7 |
|
|---|
| 8 | /**
|
|---|
| 9 | * Public function `stringify`.
|
|---|
| 10 | *
|
|---|
| 11 | * Returns a promise and asynchronously serialises a data structure to a
|
|---|
| 12 | * JSON string. Sanely handles promises, buffers, maps and other iterables.
|
|---|
| 13 | *
|
|---|
| 14 | * @param data: The data to transform
|
|---|
| 15 | *
|
|---|
| 16 | * @option space: Indentation string, or the number of spaces
|
|---|
| 17 | * to indent each nested level by.
|
|---|
| 18 | *
|
|---|
| 19 | * @option promises: 'resolve' or 'ignore', default is 'resolve'.
|
|---|
| 20 | *
|
|---|
| 21 | * @option buffers: 'toString' or 'ignore', default is 'toString'.
|
|---|
| 22 | *
|
|---|
| 23 | * @option maps: 'object' or 'ignore', default is 'object'.
|
|---|
| 24 | *
|
|---|
| 25 | * @option iterables: 'array' or 'ignore', default is 'array'.
|
|---|
| 26 | *
|
|---|
| 27 | * @option circular: 'error' or 'ignore', default is 'error'.
|
|---|
| 28 | *
|
|---|
| 29 | * @option yieldRate: The number of data items to process per timeslice,
|
|---|
| 30 | * default is 16384.
|
|---|
| 31 | *
|
|---|
| 32 | * @option bufferLength: The length of the buffer, default is 1024.
|
|---|
| 33 | *
|
|---|
| 34 | * @option highWaterMark: If set, will be passed to the readable stream constructor
|
|---|
| 35 | * as the value for the highWaterMark option.
|
|---|
| 36 | *
|
|---|
| 37 | * @option Promise: The promise constructor to use, defaults to bluebird.
|
|---|
| 38 | **/
|
|---|
| 39 | function stringify (data, options) {
|
|---|
| 40 | const json = []
|
|---|
| 41 | const Promise = promise(options)
|
|---|
| 42 | const stream = streamify(data, options)
|
|---|
| 43 |
|
|---|
| 44 | let resolve, reject
|
|---|
| 45 |
|
|---|
| 46 | stream.on('data', read)
|
|---|
| 47 | stream.on('end', end)
|
|---|
| 48 | stream.on('error', error)
|
|---|
| 49 | stream.on('dataError', error)
|
|---|
| 50 |
|
|---|
| 51 | return new Promise((res, rej) => {
|
|---|
| 52 | resolve = res
|
|---|
| 53 | reject = rej
|
|---|
| 54 | })
|
|---|
| 55 |
|
|---|
| 56 | function read (chunk) {
|
|---|
| 57 | json.push(chunk)
|
|---|
| 58 | }
|
|---|
| 59 |
|
|---|
| 60 | function end () {
|
|---|
| 61 | resolve(json.join(''))
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | function error (e) {
|
|---|
| 65 | reject(e)
|
|---|
| 66 | }
|
|---|
| 67 | }
|
|---|