Skip to main content

Node Streams

'Aaahh be like water', Bruce Lee said, 'be like water'. Streams flow and you manage them with piping, just like plumbing.

source.pipe(destination)

So to take input from the terminal (stdin), and redirect it out (stdout) we would do something like this:

process.stdin.pipe(process.stdout)

So whatever character you type, you see it duplicated.

In node all streams are instances of EventEmitter. request, response are readable and writeable streams, inheriting from EventEmitter.

Request events:

readable
end

Example event emitter:

const EventEmitter = require('events').EventEmitter;

let tagEvents = new EventEmitter();
let tags = [];
let update = (() => {
  let counter = 0;
  return () => {
    return counter++;
  };

}());

tagEvents.on('update', () => {
  tags.push(update());
  return tags;
});

tagEvents.get = function () {
  return tags;
};
console.log(tagEvents.emit('update'));
// true
console.log(tagEvents.get());
// [ 0 ]
console.log(tagEvents.emit('update'));
// true
console.log(tagEvents.get());
// [ 0, 1 ]
console.log(tagEvents.emit('update'));
// true
console.log(tagEvents.get());
// [ 0, 1, 2 ]
console.log(tagEvents.emit('update'));
// true
console.log(tagEvents.get());
// [ 0, 1, 2, 3 ]
console.log(tagEvents.emit('update'));
// true
console.log(tagEvents.get());
// [ 0, 1, 2, 3, 4 ]

Another:

var emitter = require("events").EventEmitter;
var logger = new EventEmitter();

logger.on("error", function (message) {
  console.log("Error: " + message);
});

logger.emit("error", "Oh no, something went wrong!");
var events = require('events');
var EventEmitter = events.EventEmitter;

var chat = new EventEmitter();
var users = [], chatlog = [];

chat.on('message', function(message) {
  chatlog.push(message);
});

chat.on('join', function(nickname) {
  users.push(nickname);
});

// Emit events here
chat.emit("join", "Custom message");
chat.emit("message", "test");

References