Search code examples
node.jstypescriptstdoutstderr

how to capture the output that a function prints to the terminal in typescript/node


I am working with a typescript/node.js codebase, where there is a function that is called normally:

func('param1', 'param2', param3')

This function does not have a return value but it will print different kinds of output to the terminal when the code is run - this output might be normal console.log statements or an error of some sort. I want to be able to capture whatever the function print out into a variable for use later on - does anyone know how to capture what the function outputs into a variable? (so I can use it in if statments later)


Solution

  • If the function use console.log to output the values, you can override it as:

    console.lg = console.log;
    
    console.log = function(arg)
    {
        console.lg(arg);
        global.myOutput = arg;
    };
    

    Then call your function and after that, check the value of global.myOutput. Also, you can pass all this logic into an object:

    const logCapture = {
     output: null,
     enable() {
      console.lg = console.log;
      const that = this;
    
      console.log = function(arg) {
        console.lg(arg);
        that.output = arg;
       };
     },
     getOutput() {
      return this.output;
     },
     disable() {
      console.log = console.lg;
      console.lg = undefined;
     }
    }
    

    And use it:

    logCapture.enable();
    callToFunction(...);
    let myVar = logCapture.getOutput();
    logCapture.disable();