co-chan - Go like channel
A go style channel implementation that works well with co.
Channel has a buffer size, and default size is 0.
Sender can await until the value pushed into buffer or until the value received by receiver.
Installation
$ npm install co-chan
Usage
co-chan does not directly use any ES2015(ES6) features, but it is designed to work well with co, a control flow library based on ES2015(ES6) generators.
The following example uses co and requires node 0.11.x
(unstable)
and must be run with the --harmony-generators
or --harmony
flag.
Future stable versions of node.js will include support for generators.
example using co generators
// require the dependenciesvar Channel = ;var co = ;var fs = ; // make a new channelvar ch = ; // execute a co generator;
send value asynchronously, await for receive value
// require the dependenciesvar Channel = ;var co = ; // make two channelsvar ch1 = ;var ch2 = ; ; ;
output:
recv: ch1 = 12
send: ch2 = 34
send: ch1 = 12
recv: ch2 = 34
await for send value, await for receive value
// require the dependenciesvar Channel = ;var co = ; // make two channelsvar ch1 = ; // default buffer size = 0var ch2 = ; ; ;
output:
recv: ch1 = 12
sent: ch1 = 12
recv: ch2 = 34
sent: ch2 = 34
recv: ch1 err Error: custom error
sent: ch1 err
recv: ch2 is empty
Appendix
without co
send value into channel, receive value from the channel
// require the dependenciesvar Channel = ; // make a new channelvar ch = ; // send value into the channel;console; // receive value from the channel;
output:
send: ch = 123
recv: ch = 123
get value from regular node function, set channel as callback function
// require the dependenciesvar Channel = ;var fs = ; // make a new channelvar ch = ; // pass the channel as the callback to filesystem read file function// this will push the file contents in to the channelfs;console; // call with callback to the channel as thunk to pull the value off the channel;
output:
read: to ch
recv: ch = this is README.md
License
MIT
Git Repository
LightSpeedWorks/co-chan