From b2fc61759e7f5c15018dcbbf15f2cdc001cd8aaa Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 8 Jun 2020 20:30:20 +0200 Subject: [PATCH 1/2] 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 --- lib/internal/util/inspect.js | 3 ++- test/parallel/test-util-inspect.js | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 9f57163df1c1fb..acf688a91e260f 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -478,7 +478,8 @@ function stylizeWithColor(str, styleType) { const style = inspect.styles[styleType]; if (style !== undefined) { const color = inspect.colors[style]; - return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`; + if (color !== undefined) + return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`; } return str; } diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 1700e4d5c636aa..1603e28bd8bd40 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -2245,6 +2245,12 @@ assert.strictEqual( assert.deepStrictEqual(inspect.colors[bgColor], [40 + i, 49]); assert.deepStrictEqual(inspect.colors[`${bgColor}Bright`], [100 + i, 49]); }); + + // Unknown colors are handled gracefully: + const stringStyle = inspect.styles.string; + inspect.styles.string = 'UNKNOWN'; + assert.strictEqual(inspect('foobar', { colors: true }), 'foobar'); + inspect.styles.string = stringStyle; } assert.strictEqual( From 61e231a7280febcf4ab3ef89ed6b0702ff78129b Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 8 Jun 2020 21:40:31 +0200 Subject: [PATCH 2/2] fixup! Signed-off-by: Ruben Bridgewater --- test/parallel/test-util-inspect.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 1603e28bd8bd40..0cf971b188a40e 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -2249,7 +2249,7 @@ assert.strictEqual( // Unknown colors are handled gracefully: const stringStyle = inspect.styles.string; inspect.styles.string = 'UNKNOWN'; - assert.strictEqual(inspect('foobar', { colors: true }), 'foobar'); + assert.strictEqual(inspect('foobar', { colors: true }), "'foobar'"); inspect.styles.string = stringStyle; }