在 node.js 中捕获 console.log? [英] Catching console.log in node.js?

查看:23
本文介绍了在 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.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));
};

这篇关于在 node.js 中捕获 console.log?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆