在node.js中捕获console.log吗?

在node.js中捕获console.log吗?

问题描述:

有没有一种方法可以在node.js中捕获由console.log(...)引起的最终控制台输出,以防止在单元测试模块时记录终端?

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 module?

谢谢

module.js:

module.js:

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

程序:

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

显然,您可以根据需要收集日志消息,以备以后使用:

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

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