tty: add hasColors function · nodejs/node@070faf0 · GitHub
Skip to content

Commit 070faf0

Browse files
BridgeARtargos
authored andcommitted
tty: add hasColors function
This adds a small wrapper around the `getColorDepth` function to check if the stream supports at least a specific amount of colors. This is convenient as the other API is not as straight forward and most use cases likely only want to know if a specific amount of colors is supported or not. PR-URL: #26247 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Weijia Wang <starkwang@126.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
1 parent 9ce08c8 commit 070faf0

5 files changed

Lines changed: 81 additions & 2 deletions

File tree

doc/api/tty.md

Lines changed: 30 additions & 0 deletions

lib/internal/tty.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222

2323
'use strict';
2424

25+
const {
26+
ERR_INVALID_ARG_TYPE,
27+
ERR_OUT_OF_RANGE
28+
} = require('internal/errors').codes;
29+
2530
let OSRelease;
2631

2732
const COLORS_2 = 1;
@@ -151,6 +156,23 @@ function getColorDepth(env = process.env) {
151156
return COLORS_2;
152157
}
153158

159+
function hasColors(count, env) {
160+
if (env === undefined &&
161+
(count === undefined || typeof count === 'object' && count !== null)) {
162+
env = count;
163+
count = 16;
164+
} else {
165+
if (typeof count !== 'number') {
166+
throw new ERR_INVALID_ARG_TYPE('count', 'number', count);
167+
}
168+
if (count < 2) {
169+
throw new ERR_OUT_OF_RANGE('count', '>= 2', count);
170+
}
171+
}
172+
return count <= 2 ** getColorDepth(env);
173+
}
174+
154175
module.exports = {
155-
getColorDepth
176+
getColorDepth,
177+
hasColors
156178
};

lib/tty.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ const net = require('net');
2626
const { TTY, isTTY } = internalBinding('tty_wrap');
2727
const errors = require('internal/errors');
2828
const { ERR_INVALID_FD, ERR_TTY_INIT_FAILED } = errors.codes;
29-
const { getColorDepth } = require('internal/tty');
29+
const {
30+
getColorDepth,
31+
hasColors
32+
} = require('internal/tty');
3033

3134
// Lazy loaded for startup performance.
3235
let readline;
@@ -109,6 +112,8 @@ WriteStream.prototype.isTTY = true;
109112

110113
WriteStream.prototype.getColorDepth = getColorDepth;
111114

115+
WriteStream.prototype.hasColors = hasColors;
116+
112117
WriteStream.prototype._refreshSize = function() {
113118
const oldCols = this.columns;
114119
const oldRows = this.rows;

test/pseudo-tty/test-tty-get-color-depth.js renamed to test/pseudo-tty/test-tty-color-support.js

Lines changed: 22 additions & 0 deletions
File renamed without changes.

0 commit comments

Comments
 (0)