SubStream is a simple stream multiplexer for Primus. It allows you to create
simple message channels which only receive the information you send to it. These
channels are in fact, streams, which is why this module is called
because it adds small streams on top of the main stream and intercepts them.
npm install --save substream
The module can only be used in conjunction with Primus so make sure that your application is using that as its real-time backend.
In all the code examples, we assume that the following code is present:
'use strict';var Primus =http = ;var server = httpprimus = server;//// Custom code here, just above the listen call.//server;
//// The `primus.use` method adds the plugin to primus. It requires a unique// name in order to easily retrieve it again. For the// sake of clarity, we're going to use 'substream' as the name.//primus;
After you've added plugins, you might want to re-compile the client library that
Primus serves, as it automatically adds the client-side plugin to the framework,
as well as the custom
substream.js library to create the actual name spaces. To
save the client just run:
But this is only needed if you serve the file manually and not through the
/primus/primus.js path (which is regenerated on the fly).
Now that we've set everything up correctly we can start creating some substreams.
To create or access a
substream in the Primus client start off with making
var primus = 'http://<your url here:whateverportnumber>';var foo = primus;
substream method automatically creates a namespaced stream if you didn't
create it before. Or, it will return your previously created stream when you call
it again. So now we have a
foo stream we can just write to:
Awesome, all works as intended. But this was just one single substream, we can add more:
var bar = primusbaz = primus;
You can create an infinite number of substreams on top of one single base stream. The data is not leaked between streams. It's all "sandboxed".
As the returned substreams are
eventemitters we can just listen
close events. But it also proxies all the other events
that Primus emits such as the
offline events etc. (The full
list is in the Primus README.md). So for receiving and writing data you can just
The server portion of this module isn't that different than the client portion. It follows the same API stream/eventemitter API:
streamsobject to the spark/connection which contains all active SubStreams for the given connection mapped by name->substream-instance