unpipe.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict'
  2. const stream = require('stream')
  3. const check = require('check-types')
  4. const parse = require('./parse')
  5. module.exports = unpipe
  6. /**
  7. * Public function `unpipe`.
  8. *
  9. * Returns a writeable stream that can be passed to stream.pipe, then parses JSON
  10. * data read from the stream. If there are no errors, the callback is invoked with
  11. * the result as the second argument. If errors occur, the first error is passed to
  12. * the callback as the first argument.
  13. *
  14. * @param callback: Function that will be called after parsing is complete.
  15. *
  16. * @option reviver: Transformation function, invoked depth-first.
  17. *
  18. * @option discard: The number of characters to process before discarding them
  19. * to save memory. The default value is `1048576`.
  20. *
  21. * @option yieldRate: The number of data items to process per timeslice,
  22. * default is 16384.
  23. **/
  24. function unpipe (callback, options) {
  25. check.assert.function(callback, 'Invalid callback argument')
  26. const jsonstream = new stream.PassThrough()
  27. parse(jsonstream, { ...options, ndjson: false })
  28. .then(data => callback(null, data))
  29. .catch(error => callback(error))
  30. return jsonstream
  31. }