Skip to content

Streams convention

Dima Yv edited this page Nov 8, 2016 · 12 revisions

From the realtime streams discussion.

Audio components provide function constructor as main export, ./stream.js for stream interface and ./pull.js for pull-stream interface.

There are three generic possible types of streams, corresponding to notions of data source, data transform and data output. In different stream worlds they are called differently, in pull-streams that is source, through and sink; in classic streams that is Readable, Transform and Writable.

In audiojs we use plain function as a default package exports, with the signatures described below. Because we can wrap any of these functions easily to any stream interface.

Source/Readable:

// sync source
module.exports = function (options) {
  return function read () {
    //return null to end
    return buffer
  }
}

// async source
module.exports = function (options) {
  //pass null as a callback to indicate the end?
  return function read (cb) {
    //cb(null, null) to end
    //cb(error) to throw error
    cb(null, buffer)
  }
}

Through/map:

// sync through
module.exports = function (options) {
  return function transform (buffer) {
    //return null to end
    return buffer
  }
}

// async through
module.exports = function (options) {
  return function transform (buffer, cb) {
    //cb(null, null) to end
    //cb(error) to throw error
    cb(null, buffer)
  }
}

Sink/destination/writable:

// sync sink
module.exports = function (options) {
  return function write (buffer) {
    // do stuff
    // throw error
    // or return null to end
  }
}

// async sink
module.exports = function (options) {
  //do end routine
  write.end = function () {}  

  return write;

  function write (buffer, cb) {
    // do stuff
    cb(err or null, data or null);
  }
}

Note that returned runction may have end method defined to explicitly end stream. That is valid for all types of streams.

Clone this wiki locally