Skip to content

Commit c6dec0f

Browse files
addaleaxBridgeAR
authored andcommitted
console: add color support
Add a way to tell `Console` instances to either always use, never use or auto-detect color support and inspect objects accordingly. PR-URL: nodejs#19372 Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent ead3f07 commit c6dec0f

File tree

5 files changed

+105
-16
lines changed

5 files changed

+105
-16
lines changed

doc/api/console.md

+7-1
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,20 @@ changes:
8787
description: The `ignoreErrors` option was introduced.
8888
- version: REPLACEME
8989
pr-url: https://github.com/nodejs/node/pull/19372
90-
description: The `Console` constructor now supports an `options` argument.
90+
description: The `Console` constructor now supports an `options` argument,
91+
and the `colorMode` option was introduced.
9192
-->
9293

9394
* `options` {Object}
9495
* `stdout` {stream.Writable}
9596
* `stderr` {stream.Writable}
9697
* `ignoreErrors` {boolean} Ignore errors when writing to the underlying
9798
streams. **Default:** `true`.
99+
* `colorMode` {boolean|string} Set color support for this `Console` instance.
100+
Setting to `true` enables coloring while inspecting values, setting to
101+
`'auto'` will make color support depend on the value of the `isTTY` property
102+
and the value returned by `getColorDepth()` on the respective stream.
103+
**Default:** `false`
98104

99105
Creates a new `Console` with one or two writable stream instances. `stdout` is a
100106
writable stream to print log or info output. `stderr` is used for warning or

doc/api/util.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -268,8 +268,8 @@ an `inspectOptions` argument which specifies options that are passed along to
268268

269269
```js
270270
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
271-
// Returns 'See object { foo: 42 }', where `42` is colored as a number
272-
// when printed to a terminal.
271+
// Returns 'See object { foo: 42 }', where `42` is colored as a number
272+
// when printed to a terminal.
273273
```
274274

275275
## util.getSystemErrorName(err)

lib/console.js

+48-13
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ const {
2626
codes: {
2727
ERR_CONSOLE_WRITABLE_STREAM,
2828
ERR_INVALID_ARG_TYPE,
29+
ERR_INVALID_ARG_VALUE,
2930
},
3031
} = require('internal/errors');
3132
const { Buffer: { isBuffer } } = require('buffer');
@@ -48,24 +49,32 @@ const {
4849
} = Array;
4950

5051
// Track amount of indentation required via `console.group()`.
51-
const kGroupIndent = Symbol('groupIndent');
52+
const kGroupIndent = Symbol('kGroupIndent');
53+
54+
const kFormatForStderr = Symbol('kFormatForStderr');
55+
const kFormatForStdout = Symbol('kFormatForStdout');
56+
const kGetInspectOptions = Symbol('kGetInspectOptions');
57+
const kColorMode = Symbol('kColorMode');
5258

5359
function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
5460
if (!(this instanceof Console)) {
5561
return new Console(...arguments);
5662
}
5763

58-
let stdout, stderr, ignoreErrors;
64+
let stdout, stderr, ignoreErrors, colorMode;
5965
if (options && typeof options.write !== 'function') {
6066
({
6167
stdout,
6268
stderr = stdout,
63-
ignoreErrors = true
69+
ignoreErrors = true,
70+
colorMode = false
6471
} = options);
6572
} else {
66-
stdout = options;
67-
stderr = arguments[1];
68-
ignoreErrors = arguments[2] === undefined ? true : arguments[2];
73+
return new Console({
74+
stdout: options,
75+
stderr: arguments[1],
76+
ignoreErrors: arguments[2]
77+
});
6978
}
7079

7180
if (!stdout || typeof stdout.write !== 'function') {
@@ -93,7 +102,11 @@ function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
93102
prop.value = createWriteErrorHandler(stderr);
94103
Object.defineProperty(this, '_stderrErrorHandler', prop);
95104

105+
if (typeof colorMode !== 'boolean' && colorMode !== 'auto')
106+
throw new ERR_INVALID_ARG_VALUE('colorMode', colorMode);
107+
96108
this[kCounts] = new Map();
109+
this[kColorMode] = colorMode;
97110

98111
Object.defineProperty(this, kGroupIndent, { writable: true });
99112
this[kGroupIndent] = '';
@@ -155,13 +168,33 @@ function write(ignoreErrors, stream, string, errorhandler, groupIndent) {
155168
}
156169
}
157170

171+
const kColorInspectOptions = { colors: true };
172+
const kNoColorInspectOptions = {};
173+
Console.prototype[kGetInspectOptions] = function(stream) {
174+
let color = this[kColorMode];
175+
if (color === 'auto') {
176+
color = stream.isTTY && (
177+
typeof stream.getColorDepth === 'function' ?
178+
stream.getColorDepth() > 2 : true);
179+
}
180+
181+
return color ? kColorInspectOptions : kNoColorInspectOptions;
182+
};
183+
184+
Console.prototype[kFormatForStdout] = function(args) {
185+
const opts = this[kGetInspectOptions](this._stdout);
186+
return util.formatWithOptions(opts, ...args);
187+
};
188+
189+
Console.prototype[kFormatForStderr] = function(args) {
190+
const opts = this[kGetInspectOptions](this._stderr);
191+
return util.formatWithOptions(opts, ...args);
192+
};
193+
158194
Console.prototype.log = function log(...args) {
159195
write(this._ignoreErrors,
160196
this._stdout,
161-
// The performance of .apply and the spread operator seems on par in V8
162-
// 6.3 but the spread operator, unlike .apply(), pushes the elements
163-
// onto the stack. That is, it makes stack overflows more likely.
164-
util.format.apply(null, args),
197+
this[kFormatForStdout](args),
165198
this._stdoutErrorHandler,
166199
this[kGroupIndent]);
167200
};
@@ -172,14 +205,16 @@ Console.prototype.dirxml = Console.prototype.log;
172205
Console.prototype.warn = function warn(...args) {
173206
write(this._ignoreErrors,
174207
this._stderr,
175-
util.format.apply(null, args),
208+
this[kFormatForStderr](args),
176209
this._stderrErrorHandler,
177210
this[kGroupIndent]);
178211
};
179212
Console.prototype.error = Console.prototype.warn;
180213

181214
Console.prototype.dir = function dir(object, options) {
182-
options = Object.assign({ customInspect: false }, options);
215+
options = Object.assign({
216+
customInspect: false
217+
}, this[kGetInspectOptions](this._stdout), options);
183218
write(this._ignoreErrors,
184219
this._stdout,
185220
util.inspect(object, options),
@@ -210,7 +245,7 @@ Console.prototype.timeEnd = function timeEnd(label = 'default') {
210245
Console.prototype.trace = function trace(...args) {
211246
const err = {
212247
name: 'Trace',
213-
message: util.format.apply(null, args)
248+
message: this[kFormatForStderr](args)
214249
};
215250
Error.captureStackTrace(err, trace);
216251
this.error(err.stack);
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const util = require('util');
5+
const { Writable } = require('stream');
6+
const { Console } = require('console');
7+
8+
function check(isTTY, colorMode, expectedColorMode) {
9+
const items = [
10+
1,
11+
{ a: 2 },
12+
[ 'foo' ],
13+
{ '\\a': '\\bar' }
14+
];
15+
16+
let i = 0;
17+
const stream = new Writable({
18+
write: common.mustCall((chunk, enc, cb) => {
19+
assert.strictEqual(chunk.trim(),
20+
util.inspect(items[i++], {
21+
colors: expectedColorMode
22+
}));
23+
cb();
24+
}, items.length),
25+
decodeStrings: false
26+
});
27+
stream.isTTY = isTTY;
28+
29+
// Set ignoreErrors to `false` here so that we see assertion failures
30+
// from the `write()` call happen.
31+
const testConsole = new Console({
32+
stdout: stream,
33+
ignoreErrors: false,
34+
colorMode
35+
});
36+
for (const item of items) {
37+
testConsole.log(item);
38+
}
39+
}
40+
41+
check(true, 'auto', true);
42+
check(false, 'auto', false);
43+
check(true, true, true);
44+
check(false, true, true);
45+
check(true, false, false);
46+
check(false, false, false);

test/parallel/test-console.js

+2
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,11 @@ const custom_inspect = { foo: 'bar', inspect: () => 'inspect' };
5151

5252
const strings = [];
5353
const errStrings = [];
54+
process.stdout.isTTY = false;
5455
common.hijackStdout(function(data) {
5556
strings.push(data);
5657
});
58+
process.stderr.isTTY = false;
5759
common.hijackStderr(function(data) {
5860
errStrings.push(data);
5961
});

0 commit comments

Comments
 (0)