{"name":"stream-demux","version":"10.2.0","keywords":["iterable","async","stream","demux","demultiplexer","for-await-of"],"author":{"name":"Jonathan Gros-Dubois"},"license":"MIT","_id":"stream-demux@10.2.0","maintainers":[{"name":"topcloudsystems","email":"grosjona@yahoo.com.au"}],"homepage":"https://github.com/SocketCluster/stream-demux#readme","bugs":{"url":"https://github.com/SocketCluster/stream-demux/issues"},"dist":{"shasum":"91a9c61e7a2fc517b3ac7334bb943a0f54e83087","tarball":"http://registry-npm.ywwl.com/stream-demux/download/stream-demux-10.2.0.tgz","fileCount":6,"integrity":"sha512-bSG8XIA6eMiO2q5qGq6INePQolqATCooEgqu8FDE1XWRhpcFhQhht3CSuPFjuYHk4BobdRwHKi2l+2CepY7N2g==","signatures":[{"sig":"MEUCIQCrRY39e615GyvFh7UY7ejpq4g4QdQOCxEVFIgv740T3AIgVLWcQyeOlu82B1GMD4eHBSrx8obZ81mk8Q0f64NKdr4=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"sig":"MEQCIHlwxvNy6K7JP1lITBEpscxlcRs9Ugx3CyxWw4E63XvoAiBo7YjnzqvcEofGAezLnHRmQvQPesiroai10XN7dMh69g==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":48884,"size":8504,"noattachment":false,"key":"/stream-demux/-/stream-demux-10.2.0.tgz"},"main":"index.js","gitHead":"0dfb487b32b53cefa422ea478e0330a4c484be6d","scripts":{"test":"mocha --reporter spec --timeout 10000 --slow 10000"},"_npmUser":{"name":"topcloudsystems","email":"grosjona@yahoo.com.au"},"repository":{"url":"git+https://github.com/SocketCluster/stream-demux.git","type":"git"},"_npmVersion":"11.6.2","description":"A consumable stream demultiplexer.","directories":{},"_nodeVersion":"24.11.1","dependencies":{"consumable-stream":"^3.0.0","writable-consumable-stream":"^5.0.0"},"_hasShrinkwrap":false,"devDependencies":{"mocha":"^12.0.3"},"_npmOperationalInternal":{"tmp":"tmp/stream-demux_10.2.0_1791517620921_0.7605858555482137","host":"s3://npm-registry-packages-npm-production"},"readme":"# stream-demux\nAn consumable stream demultiplexer.\n\nLets you write data to multiple consumable streams from a central place without keeping any references to those streams.\nThe `StreamDemux` class returns streams of class `DemuxedConsumableStream` (base class `ConsumableStream`).  \nSee https://github.com/SocketCluster/consumable-stream\n\nThis library uses a queue which is implemented as a singly-linked list; this allows each loop to consume at its own pace without missing any events (supports nested await statements). An 'event' in the queue can be garbage-collected as soon as the slowest consumer moves its pointer past it.\n\n## Installation\n\n```\nnpm install stream-demux\n```\n\n## Usage\n\n### Consuming using async loops\n\n```js\nlet demux = new StreamDemux();\n\n(async () => {\n  // Consume data from 'abc' stream.\n  let substream = demux.stream('abc');\n  for await (let packet of substream) {\n    console.log('ABC:', packet);\n  }\n})();\n\n(async () => {\n  // Consume data from 'def' stream.\n  let substream = demux.stream('def');\n  for await (let packet of substream) {\n    console.log('DEF:', packet);\n  }\n})();\n\n(async () => {\n  // Consume data from 'def' stream.\n  // Can also work with a while loop for older environments.\n  // Can have multiple loops consuming the same stream at\n  // the same time.\n  // Note that you can optionally pass a number n to the\n  // createConsumer(n) method to force the iteration to\n  // timeout after n milliseconds of inactivity.\n  let consumer = demux.stream('def').createConsumer();\n  while (true) {\n    let packet = await consumer.next();\n    if (packet.done) break;\n    console.log('DEF (while loop):', packet.value);\n  }\n})();\n\n(async () => {\n  for (let i = 0; i < 10; i++) {\n    await wait(10);\n    demux.write('abc', 'message-abc-' + i);\n    demux.write('def', 'message-def-' + i);\n  }\n  demux.close('abc');\n  demux.close('def');\n})();\n\n// Utility function for using setTimeout() with async/await.\nfunction wait(duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve();\n    }, duration);\n  });\n}\n```\n\n### Consuming using the once method\n\n```js\n// Log the next received packet from the abc stream.\n(async () => {\n  // The returned promise never times out.\n  let packet = await demux.stream('abc').once();\n  console.log('Packet:', packet);\n})();\n\n// Same as above, except with a timeout of 10 seconds.\n(async () => {\n  try {\n    let packet = await demux.stream('abc').once(10000);\n    console.log('Packet:', packet);\n  } catch (err) {\n    // If no packets are written to the 'abc' stream before\n    // the timeout, an error will be thrown and handled here.\n    // The err.name property will be 'TimeoutError'.\n    console.log('Error:', err);\n  }\n})();\n```\n\n## Consumer lifetime\n\nA `StreamDemux` owns its streams; each one is created on demand when a consumer\nasks for it by name and is dropped as soon as its last consumer goes away. That\nis why no cleanup is needed beyond ending consumption, which you do by breaking\nout of the `for-await-of` loop, or by calling `consumer.return()`, `kill()` or\n`killAll()`.\n\nA consequence is that a consumer must not be reused once its iteration has\nended. Create a new one instead:\n\n```js\nlet consumer = demux.stream('abc').createConsumer();\nfor await (let packet of consumer) {\n  if (packet === 'stop') break;\n}\n\n// Do not iterate `consumer` again; ask the demux for a new one.\nlet nextConsumer = demux.stream('abc').createConsumer();\n```\n\nReusing a consumer after its loop has ended leaves it attached to a stream the\ndemux has already dropped, so it will never receive anything written through\n`demux.write()` and cannot be reached by `kill()` or `close()`. (A consumer\ncreated directly on a `WritableConsumableStream` *can* be reused, because there\nthe stream's lifetime is yours to manage rather than the demux's.)\n\n`demux.unstream(streamName)` detaches a stream from the demux and kills its\nconsumers, so their loops end rather than hanging on a stream nothing can\nreach any more.\n\n## Goal\n\nThe goal of this module is to facilitate functional programming patterns which decrease the probability of memory leaks and race conditions.\nIt serves as an alternative to callback-based event handling.\n","publish_time":1791517621008,"_cnpm_publish_time":1791517621008,"dist-tags":{"latest":"10.2.1"}}