Skip to content

Instantly share code, notes, and snippets.

@stringparser
Last active April 3, 2022 06:09
Show Gist options
  • Save stringparser/b539b8cfd5769542037d to your computer and use it in GitHub Desktop.
Save stringparser/b539b8cfd5769542037d to your computer and use it in GitHub Desktop.
node stdout hook with knobs

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment