UNPKG

1.72 kBJavaScriptView Raw
1"use strict";
2
3const clc = require("cli-color");
4
5/**
6 * @param {boolean} enableColor
7 * @param {stream.Writable} stdout
8 * @param {stream.Readable} stderr
9 * @constructor
10 */
11const Logger = function(enableColor, stdout, stderr) {
12 this.color_ = !!enableColor;
13 this.messages_ = [];
14 this.stdout = stdout;
15 this.stderr = stderr;
16};
17
18/**
19 * @param {string} msg
20 * @param {function(string)=} opt_color
21 */
22Logger.prototype.raw = function(msg, opt_color) {
23 this.messages_.push(this.color_ && opt_color ? opt_color(msg) : msg);
24};
25
26/**
27 * @param {string} msg
28 */
29Logger.prototype.info = function(msg) {
30 this.raw(msg);
31};
32
33/**
34 * @param {string} msg
35 */
36Logger.prototype.warn = function(msg) {
37 this.raw(msg, clc.yellow);
38};
39
40/**
41 * @param {string} msg
42 */
43Logger.prototype.error = function(msg) {
44 this.raw(msg, clc.red);
45};
46
47/**
48 * @param {string} msg
49 */
50Logger.prototype.success = function(msg) {
51 this.raw(msg, clc.green);
52};
53
54/**
55 * Log items with black bright.
56 * @param {Array<string>} items
57 */
58Logger.prototype.items = function(items) {
59 if (items.length === 0) {
60 items = ["(none)"];
61 }
62 this.messages_ = this.messages_.concat(
63 items.map(function(item) {
64 item = `- ${item}`;
65 return this.color_ ? clc.blackBright(item) : item;
66 }, this)
67 );
68};
69
70/**
71 * Flush out all stored messages.
72 * @param {boolean} success If true, flush to stdout. Otherwise to stderr.
73 */
74Logger.prototype.flush = function(success) {
75 const out = success ? this.stdout : this.stderr;
76 this.messages_.forEach(msg => {
77 out.write(`${msg}\n`);
78 });
79 this.empty();
80};
81
82/**
83 * Clear all stored messages.
84 */
85Logger.prototype.empty = function() {
86 this.messages_ = [];
87};
88
89module.exports = Logger;