在node.js中捕获console.log?

有没有一种方法可以捕获由node.js中的console.log(...)引起的最终控制台输出,以防止在unit testing模块时阻塞terminal?

谢谢

module.js:

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

程序:

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

编辑:显然,如果你愿意,你可以稍后收集日志消息:

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

一个更好的方法可能是直接挂接你需要捕获数据的输出,因为用Linus方法,如果某个模块直接写到stdout中,例如process.stdout.write('foo') ,它就不会被捕获。

 var logs = [], hook_stream = function(_stream, fn) { // Reference default write method var old_write = _stream.write; // _stream now write with our shiny function _stream.write = fn; return function() { // reset to the default write method _stream.write = old_write; }; }, // hook up standard output unhook_stdout = hook_stream(process.stdout, function(string, encoding, fd) { logs.push(string); }); // goes to our custom write method console.log('foo'); console.log('bar'); unhook_stdout(); console.log('Not hooked anymore.'); // Now do what you want with logs stored by the hook logs.forEach(function(_log) { console.log('logged: ' + _log); }); 

编辑

console.log()用一个换行符结束它的输出,你可能想要去除它,所以你最好写:

 _stream.write = function(string, encoding, fd) { var new_str = string.replace(/\n$/, ''); fn(new_str, encoding, fd); }; 

编辑

改进的通用方法可以在具有asynchronous支持的任何对象的任何方法上执行此操作请参阅要点 。

只需将以下代码片段添加到您的代码中,您就可以捕获日志,并将其打印在控制台中:

 var log = []; console.log = function(d) { log.push(d); process.stdout.write(d + '\n'); };