Skip to content

Commit 524b230

Browse files
BridgeARcodebytere
authored andcommitted
util: gracefully handle unknown colors
This makes sure colors that are unknown won't cause an error. This is especially important in case a library wants to use colors defined by Node.js core, if available and fall back to the default otherwise. Signed-off-by: Ruben Bridgewater <[email protected]> PR-URL: #33797 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Evan Lucas <[email protected]> Reviewed-By: Yongsheng Zhang <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]>
1 parent 0197ea4 commit 524b230

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

lib/internal/util/inspect.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,8 @@ function stylizeWithColor(str, styleType) {
473473
const style = inspect.styles[styleType];
474474
if (style !== undefined) {
475475
const color = inspect.colors[style];
476-
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
476+
if (color !== undefined)
477+
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
477478
}
478479
return str;
479480
}

test/parallel/test-util-inspect.js

+6
Original file line numberDiff line numberDiff line change
@@ -2240,6 +2240,12 @@ assert.strictEqual(
22402240
assert.deepStrictEqual(inspect.colors[bgColor], [40 + i, 49]);
22412241
assert.deepStrictEqual(inspect.colors[`${bgColor}Bright`], [100 + i, 49]);
22422242
});
2243+
2244+
// Unknown colors are handled gracefully:
2245+
const stringStyle = inspect.styles.string;
2246+
inspect.styles.string = 'UNKNOWN';
2247+
assert.strictEqual(inspect('foobar', { colors: true }), "'foobar'");
2248+
inspect.styles.string = stringStyle;
22432249
}
22442250

22452251
assert.strictEqual(

0 commit comments

Comments
 (0)