Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created September 6, 2013 18:58
Show Gist options
  • Save cowboy/6468351 to your computer and use it in GitHub Desktop.
Save cowboy/6468351 to your computer and use it in GitHub Desktop.
Node.js: muxing logger
var es = require('event-stream');
var util = require('util');
function Logger() {
this.stream = es.through();
this._streamWrite = this.stream.write.bind(this.stream);
this._streamEnd = this.stream.end.bind(this.stream);
this.stream.write = this.stream.end = function() {};
}
Logger.prototype.log = function(msg) {
var line = util.format('[log] %s', msg);
this._streamWrite(line + '\n');
};
Logger.prototype.bufferedStream = function() {
var buffered = es.split();
var self = this;
buffered.pipe(es.through(function(line) {
self._streamWrite(line + '\n');
}));
return buffered;
};
var logger = new Logger();
logger.stream.pipe(process.stdout);
console.log('-- start --');
logger.log('1');
var evil = es.through();
evil.pipe(logger.stream); // pipe to the main stream? O NOES
evil.write('THIS SHOULD BREAK NOTHING'); evil.end();
var s1 = logger.bufferedStream();
s1.write('a');
logger.log('2');
s1.write('b');
logger.log('3');
s1.write('c'); s1.end();
logger.log('4');
var s2 = logger.bufferedStream();
var t2 = es.through(function(s) { this.queue(s.toUpperCase()); });
t2.pipe(s2);
t2.write('d');
logger.log('5');
t2.write('e');
t2.write('f'); t2.end();
logger.log('6');
console.log('-- end --');
-- start --
[log] 1
[log] 2
[log] 3
abc
[log] 4
[log] 5
DEF
[log] 6
-- end --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment