Created
December 5, 2010 23:51
-
-
Save pguillory/729616 to your computer and use it in GitHub Desktop.
Hooking into Node.js stdout
This file contains 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 util = require('util') | |
function hook_stdout(callback) { | |
var old_write = process.stdout.write | |
process.stdout.write = (function(write) { | |
return function(string, encoding, fd) { | |
write.apply(process.stdout, arguments) | |
callback(string, encoding, fd) | |
} | |
})(process.stdout.write) | |
return function() { | |
process.stdout.write = old_write | |
} | |
} | |
console.log('a') | |
console.log('b') | |
var unhook = hook_stdout(function(string, encoding, fd) { | |
util.debug('stdout: ' + util.inspect(string)) | |
}) | |
console.log('c') | |
console.log('d') | |
unhook() | |
console.log('e') | |
console.log('f') |
This one works with AWS Lambda:
function hookStdout(callback) {
const boundProcessStdout = process.stdout.write.bind(process.stdout)
const boundProcessStderr = process.stderr.write.bind(process.stderr)
process.stdout.write = (string, encoding, fd) => {
boundProcessStdout(string, encoding, fd)
callback(string, encoding, fd, false)
}
process.stderr.write = (string, encoding, fd) => {
boundProcessStderr(string, encoding, fd)
callback(string, encoding, fd, true)
}
return () => {
process.stdout.write = boundProcessStdout
process.stderr.write = boundProcessStderr
}
}
thanks for this.
Thank you so much for this! I'm trying to make an advanced CLI for a nextjs app, but webpack uses stdout
and messes up all of the formatting!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This implementation redirects both
stdout
andstderr
to a log file:It should print in the console
and in the log file: