Skip to content

Instantly share code, notes, and snippets.

@MauroJr
Created June 21, 2017 14:37
Show Gist options
  • Save MauroJr/2e30175b59ea5da9d478d9c976b5aed1 to your computer and use it in GitHub Desktop.
Save MauroJr/2e30175b59ea5da9d478d9c976b5aed1 to your computer and use it in GitHub Desktop.

Revisions

  1. MauroJr created this gist Jun 21, 2017.
    38 changes: 38 additions & 0 deletions telnet-client.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    var _ = require('lodash'),
    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;
    };
    };