Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Last active May 19, 2017 09:11
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 karlpokus/fcda84552f0059d902c7ad2cc9ed5c43 to your computer and use it in GitHub Desktop.
Save karlpokus/fcda84552f0059d902c7ad2cc9ed5c43 to your computer and use it in GitHub Desktop.
Streams in node

stream error handling

var a
 .on('error', handleError)
 .pipe(b)
 .on('error', handleError)
 .pipe(c)
 .on('error', handleError);

reader

  • pull
  • push
  • antingen subriscribe to the data event OR .resume()
reader.prototype._read = function(size) {
  this.push(23); // emits 'data'
  this.push(null); // emits 'end'
}
writer
 .write(str | buffer)
 .end

all data can be modelled as a stream (not just I/O)

transformStream._flush is called after reader calls 'end'

buildPage

var readFile = fs.createReadStream('./lib/base.html'),
    outfile = () ? : ,
    writeFile = fs.createWriteStream(outFile)

readFile
 .pipe(addPosts)
 .pipe(addPaginator)
 .pipe(writeFile)

transform
  ._transform = function(chunk, enc, cb)
    // add html - no push
    this._html += toHtml(chunk.toString())
  ._flush = function(cb)
    // add posts
    // add paginator

invisible NSA stream

transformer._transform = funciton(chunk, enc, cb) this._length += chunk.length; this.push(chunk); cb();

transformer._flush = function(cb) this.emit('length', this._length); cb();


weather_sample - example stream

req
  .pipe(request)
  .pipe(compileWeather)
  .on('error', next) // called by whom?
  .on('end', next) // called by compile..?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment