【发布时间】:2012-03-25 10:45:12
【问题描述】:
有没有办法在 node.js 中捕获由console.log(...) 引起的最终控制台输出,以防止在单元测试模块时阻塞终端?
谢谢
【问题讨论】:
有没有办法在 node.js 中捕获由console.log(...) 引起的最终控制台输出,以防止在单元测试模块时阻塞终端?
谢谢
【问题讨论】:
capture-console很好地解决了这个问题。
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
});
以后
拦截
您应该知道,所有
capture函数仍会将值传递给主 stdiowrite()函数,因此日志记录仍将转到您的标准 IO 设备。如果不希望这样做,您可以使用
intercept函数。与上面显示的函数相比,这些函数实际上是s/capture/intercept,唯一的区别是调用不会转发到基本实现。
【讨论】:
只需将以下 sn-p 添加到您的代码中,您就可以捕获日志并仍将其打印在控制台中:
var log = [];
console.log = function(d) {
log.push(d);
process.stdout.write(d + '\n');
};
【讨论】:
更好的方法可能是直接连接您需要捕获数据的输出,因为使用 Linus 方法,如果某些模块直接使用 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);
};
编辑
改进的通用方法可以在任何对象的任何方法上执行此操作,支持异步See the gist。
【讨论】:
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));
};
【讨论】: