statestream
Really simple way to create HTTP streams of state and not just events.
$ npm install statestream
How to use?
var statestream = ;var xp = ; var mystate = can: be: a: 'very complex state' ;xp;
Now, GET requests to /mystate will not be terminated and every time mystate
will be updated,
the updated object will be sent (entirely) to the client.
API
statestream(state, [options])
Returns a function(req, res)
that will handle HTTP requests in the following way:
- The URL pathname is used to define the path within the object you wish to subscribe to (e.g.
foo/goo
will returnstate.foo.goo
ornull
if not found). - It will return an
application/json
response with the current contents ofstate
- It will maintain an open connection to the client.
- It will write the contents of this object to the response stream when the object changes.
options.interval
defines the interval (in ms) for monitoring the state object (or the result of the function) for changes.
state
can either be an object or an asynchronous function that returns the new object to stream.
Passing an object:
var myobj = x: 12 ;var handler = ;// ...
Passing an async function:
var { fs;}; var handler = ;// ...
statestream.onchange(state, [options], callback)
A lower-level function that calls callback
whenever state
changes (state
can also be a function).
statestream.objpath(obj, path)
Returns the sub-objects addressed by path
in obj
.
Example (w/ express)
This example shows how to use statestream as an express middleware.
It can also be used with connect
or just inside a regular http handler.
Server
var xp = ;var statestream = ; var app = xp;var state = foo: 1 goo: 1 ; app; ; console;console; app;
Client
$ curl http://localhost:5000/mystate^C $ curl http://localhost:5000/mystate/foo # yes, you can also access sub-objects using url paths 848688^C
LICENSE
MIT