UNPKG

2.32 kBJavaScriptView Raw
1'use strict';
2
3const { indent } = require('./string');
4const { msDiff } = require('./stopwatch');
5const chalk = require('chalk');
6
7const TOO_LONG = 10;
8
9const start = process.hrtime();
10let last = null;
11
12exports.BELL = '\x07';
13// Silent during testing by default
14exports.silent = process.env.NODE_ENV == 'test';
15exports.verbose = false;
16
17/**
18 * Print 'msg' to console, with indentation level
19 * @param {String} msg
20 * @param {Int} column
21 */
22exports.print = function(msg, column) {
23 if (column == null) column = 0;
24 if (!exports.silent) console.log(indent(msg, column));
25};
26
27/**
28 * Print 'err' to console, with error colour and indentation level
29 * @param {Object|String} err
30 * @param {Int} column
31 * @param {Boolean} throws
32 * @returns {null}
33 */
34exports.error = function(err, column, throws) {
35 if (exports.silent) return;
36 if (column == null) column = 0;
37 if (throws == null) throws = true;
38 if ('string' == typeof err) err = new Error(err);
39 // Add beep when not throwing
40 if (!throws) err.message += exports.BELL;
41 exports.print(
42 chalk.red.inverse(' error ') + ' ' + err.message + (err.filepath ? ' in ' + chalk.bold.grey(err.filepath) : ''),
43 column
44 );
45 if (!throws) return console.log(err);
46 throw err;
47};
48
49/**
50 * Print 'msg' to console, with warning colour and indentation level
51 * @param {String} msg
52 * @param {Int} column
53 */
54exports.warn = function(msg, column) {
55 if (column == null) column = 0;
56 if ('string' instanceof Error) msg = msg.message;
57 exports.print(`${chalk.yellow.inverse(' warning ')} ${msg}`, column);
58};
59
60/**
61 * Print 'msg' to console, with debug colour and indentation level
62 * @param {String} msg
63 * @param {Int} column
64 */
65exports.debug = function(msg, column) {
66 const now = process.hrtime();
67
68 if (!last) last = now;
69
70 const ellapsed = msDiff(now, last);
71
72 if (column == null) column = 0;
73 if (exports.verbose) {
74 msg = chalk.cyan('+') +
75 chalk.bold.grey((ellapsed > TOO_LONG ? chalk.red(ellapsed) : ellapsed) + 'ms') +
76 chalk.cyan('::') +
77 chalk.bold.grey(msDiff(now, start) + 'ms') +
78 chalk.cyan('=') +
79 msg;
80 exports.print(msg, column);
81 }
82 last = now;
83};
84
85/**
86 * Colourize 'string' for emphasis
87 * @param {String} string
88 * @returns {String}
89 */
90exports.strong = function(string) {
91 return chalk.bold.grey(string);
92};