a9da17d353eff86e5038e015e8202fbbf818018245d3bb7d49d4c5990d55f637f2d5472df46da3fd087c3f6017ea44d0c96e4016852234666438a9894413c2 1.7 KB

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