首页 > 关于Node.js中util.debuglog(section)的疑问?

关于Node.js中util.debuglog(section)的疑问?

在学习Node.js时候,看官网文档,在util模块中,关于util.debuglog(section)的描述不太理解:
util.debuglog(section)
section: String The section of the program to be debugged
Returns: Function The logging function
This is used to create a function which conditionally writes to stderr based on the existence of a NODE_DEBUG environment variable. If the section name appears in that environment variable, then the returned function will be similar to console.error(). If not, then the returned function is a no-op.

  1. 问题如下:
    1) section具体代表什么?

2) 正确的例子是什么?我不太理解官网上的例子:

var debuglog = util.debuglog('foo');

var bar = 123;
debuglog('hello from foo [%d]', bar);

其中,foo指的是模块的话,可是我运行后没出现任何的结果(我自己定义了模块foo)


看源代码就知道了

var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
  if (debugEnviron === undefined)
    debugEnviron = process.env.NODE_DEBUG || '';
  set = set.toUpperCase();
  if (!debugs[set]) {
    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
      var pid = process.pid;
      debugs[set] = function() {
        var msg = exports.format.apply(exports, arguments);
        console.error('%s %d: %s', set, pid, msg);
      };
    } else {
      debugs[set] = function() {};
    }
  }
  return debugs[set];
};
【热门文章】
【热门文章】