AIO/Patterns and Examples

From CommonJS Spec Wiki
< AIO
Jump to: navigation, search
// Starts piping from streamA into streamB in the background and returns a concurrent promise
streamA.pipeTo(streamB);
 
// Start up two processes
var cmdA = Process.start("cmdA");
var cmdB = Process.start("cmdB");
 
// Wrap some data in a ByteBufferStream and pipe it into the stdin of the first command
new ByteBufferStream(someData).pipeTo(cmdA.stdin);
// Pipe the first command's stdout into the second command's stdin
cmdA.stdout.pipeTo(cmdB.stdin);
// The stdout of the second command can be read
cmdB.stdout; // ...
 
// An example use... a poor man's gzip libraryless gzip
var gzip = Process.start("gzip");
new ByteBufferStream(someData).pipeTo(gzip.stdin);
gzip.stdout.pipeTo(...); // ... would be a stream such as the output stream for a http request
 
/** Transfering data from one stream to another **/
// High-Level //
// This starts the piping in the background in a separate thread, it returns a
// concurrent promise you can wait on or register an async callback
from.pipeTo(to);
 
// Mid-Level //
// This transfers data from one stream to another without using any js level buffer
// In some cases like in Java where one of the streams is backed by a file
// this can even try and avoid a deal of unnecessary copying.
while ( !from.eof )
	from.transferTo(to, 1024);
 
// Low-Level
var buf = new ByteBuffer(1024);
// ...
buf.clear();
 
while ( from.read(buf) >= 0 || buf.position ) { // If we read some data, or still have unwritten data
  buf.???(); // java calls it flip; We ready the buffer for writing by setting the limit to the position and resetting the position to 0
  to.write(buf);
  buf.???();  // java calls it compact; The buffer is prepared in a way so that the next .read will put data into the unused portion of the buffer
}