简体   繁体   中英

Use node to capture stdout of function call

I have a function myFunc that writes to stdout when called. Is it possible in node.js to capture this output and store it in a variable, and make sure the output does not appear in the terminal?

If the output from the function call is done via console.log() , then you can temporarily replace console.log() with your own version that captures the output:

function myFunc() {
    console.log("this is some output", "to stdout");
}

console.data = "";

// replace console.log
console.logX = console.log;
console.log = function(...args) {
    console.data += args.join(" ") + "\n";
}

myFunc();

// restore console.log
console.log = console.logX;

// console.data contains the capture data

console.log("all done now");

If you want things other than strings (like objects) to output correctly, you will have to do more work in your own console.log() to properly display objects. This version will work fine for things that are already strings or convert easily to strings (strings, numbers, boolean).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM