Created
November 14, 2020 09:58
-
-
Save elmpp/cd412b13c2de03f1e5fde71fdf6bb5eb to your computer and use it in GitHub Desktop.
Monkey patch process.stdout to allow file logging (disappearing streams anyone?)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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