Skip to content

Instantly share code, notes, and snippets.

@nucleardreamer
Forked from benbuckman/intercept-stdout.js
Last active August 29, 2015 14:13
Show Gist options
  • Save nucleardreamer/8596f6e4c8a7d40a5ec8 to your computer and use it in GitHub Desktop.
Save nucleardreamer/8596f6e4c8a7d40a5ec8 to your computer and use it in GitHub Desktop.
var _ = require('underscore'),
util = require('util');
// intercept stdout, passes thru callback
// also pass console.error thru stdout so it goes to callback too
// (stdout.write and stderr.write are both refs to the same stream.write function)
// returns an unhook() function, call when done intercepting
module.exports = function interceptStdout(callback) {
var old_stdout_write = process.stdout.write,
old_console_error = console.error;
process.stdout.write = (function(write) {
return function(string, encoding, fd) {
var args = _.toArray(arguments);
write.apply(process.stdout, args);
// only intercept the string
callback.call(callback, string);
};
}(process.stdout.write));
console.error = (function(log) {
return function() {
var args = _.toArray(arguments);
args.unshift('[ERROR]');
console.log.apply(console.log, args);
// string here encapsulates all the args
callback.call(callback, util.format(args));
};
}(console.error));
// puts back to original
return function unhook() {
process.stdout.write = old_stdout_write;
console.error = old_console_error;
};
};
var server = require('net').createServer();
server.listen(5000, function() {
console.log('Telnet server running on port', server.address().port);
});
server.on('connection', function(socket) {
// pipe logs to telnet for the duration of connection
var unhookStdout = require('./intercept-stdout')(function intercept(string){
socket.write(string);
});
console.log('is this going to telnet?');
socket.on('end', function(){
unhookStdout();
});
socket.on('data', function(data) {
socket.setEncoding('utf8');
// should only be 1 line at a time
data = data.toString().replace(/(\r\n|\n|\r)/gm,"");
switch(data) {
case 'quit':
socket.write('Goodbye.\n');
socket.end();
break;
case 'test':
setInterval(function() { console.log(Date()); }, 500);
break;
default:
socket.write('\nUnknown command: ' + data + '\n');
}
});
});
// test intercept w/ terminal
var _ = require('underscore'),
util = require('util');
// to stdout
console.log('a', 1, {a:'b'});
console.log('b', 1, {a:'b'});
util.debug('intercept on');
var unhook = require('./intercept-stdout')(function intercept(){
var args = _.toArray(arguments);
util.debug.apply(this, args);
});
// intercepted
console.log('c', 1, {a:'b'});
console.log('d', 1, {a:'b'});
console.error('error e', 1, {a:'b'});
// back to stdout
unhook();
util.debug('Unhooked');
console.log('f back', 1, {a:'b'});
console.error('g error back', 1, {a:'b'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment