node-debugger
Version:
74 lines (57 loc) • 1.38 kB
JavaScript
var prev = {},
prevColor = 0,
sec = 1000,
min = 60 * 1000,
hour = 60 * min,
colors = [
32, // green
33, // yellow
34, // blue
35, // magenta
36, // cyan
37, // white
38,
],
others = [
31, // red
90, // grey
];
function stylize(str, color) {
if (color) return "\x1B[" + color + "m" + str + "\x1B[39m";
return str;
}
function color() {
return colors[prevColor++ % colors.length];
}
function humanize(ms) {
var sec = 1000,
min = 60 * 1000,
hour = 60 * min;
return (
ms >= hour ? (ms / hour).toFixed(1) + "h" :
ms >= min ? (ms / min).toFixed(1) + "m" :
ms >= sec ? (ms / sec | 0) + "s" :
ms + "ms"
);
}
function debug(name) {
var c = color();
return function(fmt) {
if (!debug.enabled && !debug[name]) return;
var curr = new Date,
font = others[1],
ms = curr - (prev[name] || curr),
tmp = c;
if (fmt instanceof Error) {
fmt = fmt.stack || fmt.message;
font = c = others[0];
}
fmt = fmt instanceof Error ? fmt.stack || fmt.message : fmt;
prev[name] = curr;
fmt = " " + stylize(name, c) + stylize(" - " + fmt, font) + stylize(" +" + humanize(ms), c);
console.log.apply(console, arguments);
c = tmp;
}
};
debug.enabled = true;
module.exports = debug;