Inspired on this other gist
function hook(callback){
var oldWrite = process.stdout.write;
var output = { str : '' };
return {
restore : function(){
process.stdout.write = oldWrite;
return this;
},
disable : function(){
var self = this;
process.stdout.write = (function(){
return function(str, enc, fd){
callback.call(self, output, { str : str, enc : enc, fd : fd });
};
})();
return this;
},
enable : function(){
var self = this;
process.stdout.write = (function(write){
return function(str, enc, fd){
write.apply(process.stdout, arguments);
callback.call(self, output, { str : str, enc : enc, fd : fd });
};
})(oldWrite);
},
output : function(){
return output;
},
str : function(){
return this.output().str;
},
clean : function(){
output = { str : '' };
return this;
},
reset : function(){
return this.disable().clean().enable();
}
};
}
var stdout = hook(function(output, obj){
output.str += obj.str;
})
stdout.disable();
console.log('a');
console.log('b');
stdout.enable();
console.log('stdout wrote : ', stdout.str() );
// stdout wrote : a
// b
stdout.restore();