Catching console.log in node.js?

前端 未结 4 768
野趣味
野趣味 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条回答
  •  鱼传尺愫
    2020-12-30 05:54

    module.js:

    module.exports = function() {
        console.log("foo");
    }
    

    program:

    console.log = function() {};
    mod = require("./module");
    mod();
    // Look ma no output!
    

    Edit: Obviously you can collect the log messages for later if you wish:

    var log = [];
    console.log = function() {
        log.push([].slice.call(arguments));
    };
    

提交回复
热议问题