Skip to content

Commit 2c48647

Browse files
BridgeARaddaleax
authored andcommittedJun 19, 2020
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 52de4cb commit 2c48647

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
@@ -508,7 +508,8 @@ function stylizeWithColor(str, styleType) {
508508
const style = inspect.styles[styleType];
509509
if (style !== undefined) {
510510
const color = inspect.colors[style];
511-
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
511+
if (color !== undefined)
512+
return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`;
512513
}
513514
return str;
514515
}

‎test/parallel/test-util-inspect.js

+6
Original file line numberDiff line numberDiff line change
@@ -2245,6 +2245,12 @@ assert.strictEqual(
22452245
assert.deepStrictEqual(inspect.colors[bgColor], [40 + i, 49]);
22462246
assert.deepStrictEqual(inspect.colors[`${bgColor}Bright`], [100 + i, 49]);
22472247
});
2248+
2249+
// Unknown colors are handled gracefully:
2250+
const stringStyle = inspect.styles.string;
2251+
inspect.styles.string = 'UNKNOWN';
2252+
assert.strictEqual(inspect('foobar', { colors: true }), "'foobar'");
2253+
inspect.styles.string = stringStyle;
22482254
}
22492255

22502256
assert.strictEqual(

0 commit comments

Comments
 (0)
Please sign in to comment.