Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created February 14, 2014 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/8995054 to your computer and use it in GitHub Desktop.
Save joyrexus/8995054 to your computer and use it in GitHub Desktop.
Stream demo
###
Demonstrate how to extend each of the stream base classes.
###
Read = require('stream').Readable
Write = require('stream').Writable
Filter = require('stream').Transform
class Counter extends Read
constructor: (@max) ->
@i = 0
super()
upto: (n) ->
@max = n
@
_read: ->
@i += 1
if @max and @i > @max
@push null
else
@push (@i + '').toString()
class Prefix extends Filter
constructor: (@insert=' ') -> super()
_transform: (data, enc, next) ->
@push @insert + data
next()
class Log extends Write
constructor: (@insert=' ') -> super()
_write: (data, enc, next) ->
process.stdout.write data + "\n"
next()
# create instances of each stream
count = new Counter
prefix = new Prefix '+ '
log = new Log
# call the pipeline
count
.upto(5)
.pipe(prefix)
.pipe(log)
###
results in the following output:
+ 1
+ 2
+ 3
+ 4
+ 5
###
###
Echo STDIN after inserting prefix
echo "hi!" | echo.coffee
+ hi!
###
Write = require('stream').Writable
Filter = require('stream').Transform
class Echo extends Write
_write: (data, enc, next) ->
process.stdout.write data.toString()
next()
class Prefix extends Filter
constructor: (@insert=' ') -> super()
_transform: (data, enc, next) ->
@push @insert + data
next()
echo = new Echo
prefix = new Prefix '+ '
process.stdin
.pipe(prefix)
.pipe(echo)

Extending a base class

Here are two simple approaches to creating a node stream.

To create a stream you want to utilize one of the predefined base classes (Readable, Writable, Duplex, and Transform) and extend the requisite methods. We'll create Writable two instances:

Write = require('stream').Writable

The standard approach is to create an instance of the based class and then override the _write method.

echo = Write()

echo._write = (data, enc, next) ->
  process.stdout.write data.toString()
  next()

process.stdin.pipe(echo)

However, we can also utilize coffeescript's class mechanism to extend the base class and then define override the method within our class.

class Log extends Write

  _write: (data, enc, next) ->
    process.stdout.write data + '\n'
    next()

log = new Log

process.stdin.pipe(log)

Our program (viz., this litcoffee file) will now print out two copies of whatever it gets on STDIN.

echo 'hi!' | coffee extend.coffee.md
hi!
hi!
coffee extend.coffee.md
hi!
hi!

^C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment