Skip to content

Instantly share code, notes, and snippets.

@elmpp
Created November 14, 2020 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elmpp/cd412b13c2de03f1e5fde71fdf6bb5eb to your computer and use it in GitHub Desktop.
Save elmpp/cd412b13c2de03f1e5fde71fdf6bb5eb to your computer and use it in GitHub Desktop.
Monkey patch process.stdout to allow file logging (disappearing streams anyone?)
var origWrite = process.stdout.write;
function monkey(callback){
// callback = callback).function || function(){ };
return ({
patch : function(cb){
var self = this;
this.state = { patched : true };
// callback = type(cb).function || callback;
process.stdout.write = function(str, enc, cb){
callback.call(self, str, enc, cb);
};
return this;
},
restore : function(data, enc, cb){
process.stdout.write = origWrite;
this.state = { restored : true };
return data ? this.write(data, enc, cb) : this;
},
listen : function(cb){
var self = this;
this.state = { patched : true, listening : true };
// callback = type(cb).function || callback;
process.stdout.write = function(str, enc, cb){
callback.call(self, str, enc, cb);
origWrite.call(scope, str, enc, cb);
};
return this;
},
log : function (/* arguments */){
this.restore();
var args = arguments;
var len = args.length;
if( typeof args[len-1] === 'string' ){
args[len-1] = args[len-1].trim();
}
console.log.apply(console, args);
return this;
},
write : function(str, enc, cb){
origWrite.call(scope, str, enc, cb);
return this;
}
}).patch();
}
monkey(
function(msg: string) {
fs.appendFileSync('/tmp/mnt/logOutput2.txt', `${msg}\n`)
this.write(`${msg}\n`)
// origWrite(`${msg}\n`)
// return origWrite(`${msg}\n`)
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment