You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.5 KiB

4 years ago
  1. # from2 [![Flattr this!](https://api.flattr.com/button/flattr-badge-large.png)](https://flattr.com/submit/auto?user_id=hughskennedy&url=http://github.com/hughsk/from2&title=from2&description=hughsk/from2%20on%20GitHub&language=en_GB&tags=flattr,github,javascript&category=software)[![experimental](http://hughsk.github.io/stability-badges/dist/experimental.svg)](http://github.com/hughsk/stability-badges) #
  2. `from2` is a high-level module for creating readable streams that properly handle backpressure.
  3. Convience wrapper for
  4. [readable-stream](http://github.com/isaacs/readable-stream)'s `ReadableStream`
  5. base class, with an API lifted from
  6. [from](http://github.com/dominictarr/from) and
  7. [through2](http://github.com/rvagg/through2).
  8. ## Usage ##
  9. [![from2](https://nodei.co/npm/from2.png?mini=true)](https://nodei.co/npm/from2)
  10. ### `stream = from2([opts], read)` ###
  11. Where `opts` are the options to pass on to the `ReadableStream` constructor,
  12. and `read(size, next)` is called when data is requested from the stream.
  13. * `size` is the recommended amount of data (in bytes) to retrieve.
  14. * `next(err)` should be called when you're ready to emit more data.
  15. For example, here's a readable stream that emits the contents of a given
  16. string:
  17. ``` javascript
  18. var from = require('from2')
  19. function fromString(string) {
  20. return from(function(size, next) {
  21. // if there's no more content
  22. // left in the string, close the stream.
  23. if (string.length <= 0) return next(null, null)
  24. // Pull in a new chunk of text,
  25. // removing it from the string.
  26. var chunk = string.slice(0, size)
  27. string = string.slice(size)
  28. // Emit "chunk" from the stream.
  29. next(null, chunk)
  30. })
  31. }
  32. // pipe "hello world" out
  33. // to stdout.
  34. fromString('hello world').pipe(process.stdout)
  35. ```
  36. ### `stream = from2.obj([opts], read)` ###
  37. Shorthand for `from2({ objectMode: true }, read)`.
  38. ### `createStream = from2.ctor([opts], read)` ###
  39. If you're creating similar streams in quick succession you can improve
  40. performance by generating a stream **constructor** that you can reuse instead
  41. of creating one-off streams on each call.
  42. Takes the same options as `from2`, instead returning a constructor which you
  43. can use to create new streams.
  44. ### See Also
  45. - [from2-array](https://github.com/binocarlos/from2-array) - Create a from2 stream based on an array of source values.
  46. - [from2-string](https://github.com/yoshuawuyts/from2-string) - Create a stream from a string. Sugary wrapper around from2.
  47. ## License ##
  48. MIT. See [LICENSE.md](http://github.com/hughsk/from2/blob/master/LICENSE.md) for details.