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)
CodePudding user response:
I would be rather creating a wrapper function which will take care of printing to console and update a global variable.
let log = function(msg){
console.log(msg);
outputLog = msg "\n";
}
Where ever you want to call the console.log, use log() instead
CodePudding user response:
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();