{"name":"stream-chain","version":"2.0.3","description":"Chain functions as transform streams.","main":"main.js","scripts":{"test":"node tests/tests.js"},"repository":{"type":"git","url":"git+https://github.com/uhop/stream-chain.git"},"keywords":["stream","chain"],"author":{"name":"Eugene Lazutkin","email":"eugene.lazutkin@gmail.com","url":"http://lazutkin.com/"},"license":"BSD-3-Clause","bugs":{"url":"https://github.com/uhop/stream-chain/issues"},"homepage":"https://github.com/uhop/stream-chain#readme","devDependencies":{"heya-unit":"^0.3.0"},"gitHead":"bf8547cc254acbd864d3bc648564241cbd8dfe61","_id":"stream-chain@2.0.3","_npmVersion":"6.1.0","_nodeVersion":"10.5.0","_npmUser":{"name":"elazutkin","email":"eugene@lazutkin.com"},"dist":{"integrity":"sha512-uCjJTDTAOgBrM2dLkS3mJGICUV3fL0eiTsGQ0bXiKU6et6/7dkTzZCp0eP1d8ZIwiWjthvQZlSx7NxMt7t1aFQ==","shasum":"9155237a719c8bb2de883c2d1af66d1546f910c9","tarball":"http://registry-npm.ywwl.com/stream-chain/download/stream-chain-2.0.3.tgz","fileCount":13,"unpackedSize":25027,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbMuyrCRA9TVsSAnZWagAA3G4P/RsQ869ZrLWIFxoK94Dl\nA1MdXCyTNRUzDl7n7y2XMtRIVQJCuK+W2hN5xcFWVvGAiGKSiDsp5E0fizUz\noJHYttn470D3RblJOfZjcUM1NQjVyt4581eecRPPFvHln1lHUre96akxI3/0\n8T75sDCx6x8EzotiS6gKfUJXAUBfuSgaQuEL8HC99i6vKcRmQuHQg3DYrJR1\nPFFQUiy268KyllsQ4CaIg4vVCZ2I6CzW+wjBoVzJIwGcBaAmWIT67+RVn/1H\n6Pn/1b/3ZJKMlLH/MVAqJdhpEwiPNXIZ9qV0nNjQ1Zsb7Xp4yjKhJ1srajmq\nsqLh7jbG7CuJSVRyXUxTtdhrPBoO1kOiboiYVagK4MkOwQ/rosytOEzoZrTN\nBMaQdjqaEfXZZHbkwnJBgGzv7Wspyqt63cGXAHVFSfXGLVlDwcI7QgkFDe1o\nXx0FJMZEuQTM+jvX7a5SpPdr82/lArUWghwifXFcSzafYW0A11o+w6xCUZcZ\nsAldJlz9IAWPDrWH/uNymJBjdFj8joFO9JdRZxTwg/2lcE8pvBpisWeA59os\nhwrL4OgQsC52YqLq3HYHJf1wZD42NXtCBcuXICRhaSJJRDzbrUcUt2o4s3ac\nvB+tz5uRTkRrjMtNhuaE9TBEialtvL4gdIo9PtA2ewsuzL9Gklfc0dkeouzH\nlycr\r\n=xVbM\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHpLOpcmJTB9CDYlAseHBTybdwowKOnx/TdSzb0wwPU2AiEA6h5XEOcEdVztQ8VD+I9nVAhB3Xkv7Jor/Py8ZysgNM4="}],"size":7092,"noattachment":false,"key":"/stream-chain/-/stream-chain-2.0.3.tgz"},"maintainers":[{"name":"elazutkin","email":"eugene@lazutkin.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/stream-chain_2.0.3_1530064043222_0.3340757621438677"},"_hasShrinkwrap":false,"readme":"# stream-chain [![NPM version][npm-img]][npm-url]\n\n[npm-img]:      https://img.shields.io/npm/v/stream-chain.svg\n[npm-url]:      https://npmjs.org/package/stream-chain\n\n`stream-chain` creates a chain of streams out of regular functions, asynchronous functions, generator functions, and existing streams, while properly handling [backpressure](https://nodejs.org/en/docs/guides/backpressuring-in-streams/). The resulting chain is represented as a [Duplex](https://nodejs.org/api/stream.html#stream_class_stream_duplex) stream, which can be combined with other streams the usual way. It eliminates a boilerplate helping to concentrate on functionality without losing the performance especially make it easy to build object mode data processing pipelines.\n\nOriginally `stream-chain` was used internally with [stream-fork](https://www.npmjs.com/package/stream-fork) and [stream-json](https://www.npmjs.com/package/stream-json) to create flexible data processing pipelines.\n\n`stream-chain` is a lightweight, no-dependencies micro-package. It is distributed under New BSD license.\n\n## Intro\n\n```js\nconst Chain = require('stream-chain');\n\nconst fs = require('fs');\nconst zlib = require('zlib');\nconst {Transform} = require('stream');\n\n// the chain will work on a stream of number objects\nconst chain = new Chain([\n  // transforms a value\n  x => x * x,\n  // returns several values\n  x => [x - 1, x, x + 1],\n  // waits for an asynchronous operation\n  async x => await getTotalFromDatabaseByKey(x),\n  // returns multiple values with a generator\n  function* (x) {\n    for (let i = x; i > 0; --i) {\n      yield i;\n    }\n    return 0;\n  },\n  // filters out even values\n  x => x % 2 ? x : null,\n  // uses an arbitrary transform stream\n  new Transform({\n    writableObjectMode: true,\n    transform(x, _, callback) {\n      // transform to text\n      callback(null, x.toString());\n    }\n  }),\n  // compress\n  zlib.createGzip()\n]);\n// log errors\nchain.on('error', error => console.log(error));\n// use the chain, and save the result to a file\ndataSource.pipe(chain).pipe(fs.createWriteStream('output.txt.gz'));\n```\n\nMaking processing pipelines appears to be easy: just chain functions one after another, and we are done. Real life pipelines filter objects out and/or produce more objects out of a few ones. On top of that we have to deal with asynchronous operations, while processing or producing data: networking, databases, files, user responses, and so on. Unequal number of values per stage, and unequal throughput of stages introduced problems like [backpressure](https://nodejs.org/en/docs/guides/backpressuring-in-streams/), which requires algorithms implemented by [streams](https://nodejs.org/api/stream.html).\n\nWhile a lot of API improvements were made to make streams easy to use, in reality, a lot of boilerplate is required when creating a pipeline. `stream-chain` eliminates most of it.\n\n## Installation\n\n```bash\nnpm i --save stream-chain\n# or: yarn add stream-chain\n```\n\n## Documentation\n\n`Chain`, which is returned by `require('stream-chain')`, is based on [Duplex](https://nodejs.org/api/stream.html#stream_class_stream_duplex). It chains its dependents in a single pipeline optionally binding `error` events.\n\nMany details about this package can be discovered by looking at test files located in `tests/` and in the source code (`index.js`).\n\n### Constructor: `new Chain(fns[, options])`\n\nThe constructor accepts the following arguments:\n\n* `fns` is an array of functions arrays or stream instances.\n  * If a value is a function, a [Transform](https://nodejs.org/api/stream.html#stream_class_stream_transform) stream is created, which calls this function with two parameters: `chunk` (an object), and an optional `encoding`. See [Node's documentation](https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback) for more details on those parameters. The function will be called in the context of the created stream.\n    * If it is a regular function, it can return:\n      * Regular value:\n        * *(deprecated since 2.1.0)* Array of values to pass several or zero values to the next stream as they are.\n          ```js\n          // produces no values:\n          x => []\n          // produces two values:\n          x => [x, x + 1]\n          // produces one array value:\n          x => [[x, x + 1]]\n          ```\n        * Single value.\n          * If it is `undefined` or `null`, no value shall be passed.\n          * Otherwise, the value will be passed to the next stream.\n          ```js\n          // produces no values:\n          x => null\n          x => undefined\n          // produces one value:\n          x => x\n          ```\n      * Special value:\n        * If it is an instance of [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or \"thenable\" (an object with a method called `then()`), it will be waited for. Its result should be a regular value.\n          ```js\n          // delays by 0.5s:\n          x => new Promise(\n            resolve => setTimeout(() => resolve(x), 500))\n          ```\n        * If it is an instance of a generator or \"nextable\" (an object with a method called `next()`), it will be iterated according to the [generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) protocol. The results should be regular values.\n          ```js\n          // produces multiple values:\n          class Nextable {\n            constructor(x) {\n              this.x = x;\n              this.i = -1;\n            }\n            next() {\n              return {\n                done:  this.i <= 1,\n                value: this.x + this.i++\n              };\n            }\n          }\n          x => new Nextable(x)\n          ```\n          `next()` can return a `Promise` according to the [asynchronous generator](https://zaiste.net/nodejs_10_asynchronous_iteration_async_generators/) protocol.\n      * Any thrown exception will be caught and passed to a callback function effectively generating an error event.\n        ```js\n        // fails\n        x => { throw new Error('Bad!'); }\n        ```\n  * If it is an asynchronous function, it can return a regular value.\n    * In essence, it is covered under \"special values\" as a function that returns a promise.\n    ```js\n    // delays by 0.5s:\n    async x => {\n      await new Promise(resolve => setTimeout(() => resolve(), 500));\n      return x;\n    }\n    ```\n  * If it is a generator function, each yield should produce a regular value.\n    * In essence, it is covered under \"special values\" as a function that returns a generator object.\n    ```js\n    // produces multiple values:\n    function* (x) {\n      for (let i = -1; i <= 1; ++i) {\n        if (i) yield x + i;\n      }\n      return x;\n    }\n    ```\n  * *(since 2.2.0)* If it is an asynchronous generator function, each yield should produce a regular value.\n    * In essence, it is covered under \"special values\" as a function that returns a generator object.\n    ```js\n    // produces multiple values:\n    async function* (x) {\n      for (let i = -1; i <= 1; ++i) {\n        if (i) {\n          await new Promise(resolve => setTimeout(() => resolve(), 50));\n          yield x + i;\n        }\n      }\n      return x;\n    }\n    ```\n  * *(since 2.1.0)* If a value is an array, it is assumed to be an array of regular functions.\n    Their values are passed in a chain. All values (including `null`, `undefined`, and arrays) are allowed\n    and passed without modifications. The last value is a subject to processing defined above for regular functions.\n    * Empty arrays are ignored.\n    * If any function returns a value produced by `Chain.final(value)` (see below), it terminates the chain using\n      `value` as the final value of the chain.\n    * This feature bypasses streams. It is implemented for performance reasons.\n  * If a value is a valid stream, it is included as is in the pipeline.\n    * [Transform](https://nodejs.org/api/stream.html#stream_class_stream_transform).\n    * [Duplex](https://nodejs.org/api/stream.html#stream_class_stream_duplex).\n    * The very first stream can be [Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable).\n      * In this case a `Chain` instance ignores all possible writes to the front, and ends when the first stream ends.\n    * The very last stream can be [Writable](https://nodejs.org/api/stream.html#stream_class_stream_writable).\n      * In this case a `Chain` instance does not produce any output, and finishes when the last stream finishes.\n      * Because `'data'` event is not used in this case, the instance resumes itself automatically. Read about it in Node's documentation:\n        * [Two modes](https://nodejs.org/api/stream.html#stream_two_modes).\n        * [readable.resume()](https://nodejs.org/api/stream.html#stream_readable_resume).\n* `options` is an optional object detailed in the [Node's documentation](https://nodejs.org/api/stream.html#stream_new_stream_duplex_options).\n  * If `options` is not specified, or falsy, it is assumed to be:\n    ```js\n    {writableObjectMode: true, readableObjectMode: true}\n    ```\n  * Always make sure that `writableObjectMode` is the same as the corresponding object mode of the first stream, and `readableObjectMode` is the same as the corresponding object mode of the last stream.\n    * Eventually both these modes can be deduced, but Node does not define the standard way to determine it, so currently it cannot be done reliably.\n  * Additionally the following custom properties are recognized:\n    * `skipEvents` is an optional flag. If it is falsy (the default), `'error'` events from all streams are forwarded to the created instance. If it is truthy, no event forwarding is made. A user can always do so externally or in a constructor of derived classes.\n\nAn instance can be used to attach handlers for stream events.\n\n```js\nconst chain = new Chain([x => x * x, x => [x - 1, x, x + 1]]);\nchain.on('error', error => console.error(error));\ndataSource.pipe(chain);\n```\n\n### Properties\n\nFollowing public properties are available:\n\n* `streams` is an array of streams created by a constructor. Its values either [Transform](https://nodejs.org/api/stream.html#stream_class_stream_transform) streams that use corresponding functions from a constructor parameter, or user-provided streams. All streams are piped sequentially starting from the beginning.\n* `input` is the beginning of the pipeline. Effectively it is the first item of `streams`.\n* `output` is the end of the pipeline. Effectively it is the last item of `streams`.\n\nGenerally, a `Chain` instance should be used to represent a chain:\n\n```js\nconst chain = new Chain([\n  x => x * x,\n  x => [x - 1, x, x + 1],\n  new Transform({\n    writableObjectMode: true,\n    transform(chunk, _, callback) {\n      callback(null, chunk.toString());\n    }\n  })\n]);\ndataSource\n  .pipe(chain);\n  .pipe(zlib.createGzip())\n  .pipe(fs.createWriteStream('output.txt.gz'));\n```\n\nBut in some cases `input` and `output` provide a better control over how a data processing pipeline should be organized:\n\n```js\nchain.output\n  .pipe(zlib.createGzip())\n  .pipe(fs.createWriteStream('output.txt.gz'));\ndataSource.pipe(chain.input);\n```\n\nPlease select what style you want to use, and never mix them together with the same object.\n\n### Static methods\n\nFollowing static methods are available:\n\n* `chain(fns[, options)` is a helper factory function, which has the same arguments as the constructor and returns a `Chain` instance.\n  ```js\n  const {chain} = require('stream-chain');\n\n  // simple\n  dataSource\n    .pipe(chain([x => x * x, x => [x - 1, x, x + 1]]));\n\n  // all inclusive\n  chain([\n    dataSource,\n    x => x * x,\n    x => [x - 1, x, x + 1],\n    zlib.createGzip(),\n    fs.createWriteStream('output.txt.gz')\n  ])\n  ```\n* *(since 2.1.0)* `final(value)` is a helper factory function, which can be used in by chained functions (see above the array of functions).\n  It returns a special value, which terminates the chain and uses the passed value as the result of the chain.\n  ```js\n  const {chain, final} = require('stream-chain');\n\n  // simple\n  dataSource\n    .pipe(chain([[x => x * x, x => 2 * x + 1]]));\n  // faster than [x => x * x, x => 2 * x + 1]\n\n  // final\n  dataSource\n    .pipe(chain([[\n      x => x * x,\n      x => final(x),\n      x => 2 * x + 1\n    ]]));\n  // the same as [[x => x * x, x => x]]\n  // the same as [[x => x * x]]\n  // the same as [x => x * x]\n\n  // final as a terminator\n  dataSource\n    .pipe(chain([[\n      x => x * x,\n      x => final(),\n      x => 2 * x + 1\n    ]]));\n  // produces no values, because the final value is undefined,\n  // which is interpreted as \"no value shall be passed\"\n  // see the doc above\n\n  // final() as a filter\n  dataSource\n    .pipe(chain([[\n      x => x * x,\n      x => x % 2 ? final() : x,\n      x => 2 * x + 1\n    ]]));\n  // only even values are passed, odd values are ignored\n\n  // if you want to be really performant...\n  const none = final();\n  dataSource\n    .pipe(chain([[\n      x => x * x,\n      x => x % 2 ? none : x,\n      x => 2 * x + 1\n    ]]));\n  ```\n* *(since 2.1.0)* `many(array)` is a helper factory function, which is used to wrap arrays to be interpreted as multiple values returned from a function.\n  At the moment it is redundant: you can use a simple array to indicate that, but a naked array is being deprecated and in future versions it will be passed as is.\n  The thinking is that using `many()` is better indicates the intention. Additionally, in the future versions it will be used by array of functions (see above).\n  ```js\n  const {chain, many} = require('stream-chain');\n\n  dataSource\n    .pipe(chain([x => many([x, x + 1, x + 2])]));\n  // currently the same as [x => [x, x + 1, x + 2]]\n  ```\n\n## Release History\n\n- 2.2.5 *Relaxed the definition of a stream (thx [Rich Hodgkins](https://github.com/rhodgkins)).*\n- 2.2.4 *Bugfix: wrong `const`-ness in the async generator branch (thx [Patrick Pang](https://github.com/patrickpang)).*\n- 2.2.3 *Technical release. No need to upgrade.*\n- 2.2.2 *Technical release. No need to upgrade.*\n- 2.2.1 *Technical release: new symbols namespace, explicit license (thx [Keen Yee Liau](https://github.com/kyliau)), added Greenkeeper.*\n- 2.2.0 *Added utilities: `take`, `takeWhile`, `skip`, `skipWhile`, `fold`, `scan`, `Reduce`, `comp`.*\n- 2.1.0 *Added simple transducers, dropped Node 6.*\n- 2.0.3 *Added TypeScript typings and the badge.*\n- 2.0.2 *Workaround for Node 6: use `'finish'` event instead of `_final()`.*\n- 2.0.1 *Improved documentation.*\n- 2.0.0 *Upgraded to use Duplex instead of EventEmitter as the base.*\n- 1.0.3 *Improved documentation.*\n- 1.0.2 *Better README.*\n- 1.0.1 *Fixed the README.*\n- 1.0.0 *The initial release.*\n","publish_time":1530064043303,"_cnpm_publish_time":1530064043303,"dist-tags":{"latest":"4.4.2"}}