Catching console.log in node.js?

前端 未结 4 769
野趣味
野趣味 2020-12-30 05:28

Is there a way that I can catch eventual console output caused by console.log(...) within node.js to prevent cloggering the terminal whilst unit testing a modu

4条回答
  •  -上瘾入骨i
    2020-12-30 05:46

    capture-console solves this problem nicely.

    var capcon = require('capture-console');
    
    var stderr = capcon.captureStderr(function scope() {
      // whatever is done in here has stderr captured,
      // the return value is a string containing stderr
    });
    
    var stdout = capcon.captureStdout(function scope() {
      // whatever is done in here has stdout captured,
      // the return value is a string containing stdout
    });
    

    and later

    Intercepting

    You should be aware that all capture functions will still pass the values through to the main stdio write() functions, so logging will still go to your standard IO devices.

    If this is not desirable, you can use the intercept functions. These functions are literally s/capture/intercept when compared to those shown above, and the only difference is that calls aren't forwarded through to the base implementation.

提交回复
热议问题