diff --git a/doc/api/util.md b/doc/api/util.md index 5839f74a6b9c29..63c32a07c36efc 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -1800,7 +1800,8 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); added: v21.7.0 --> -* `format` {string} A text format defined in `util.inspect.colors`. +* `format` {string | Array} A text format or an Array + of text formats defined in `util.inspect.colors`. * `text` {string} The text to to be formatted. This function returns a formatted text considering the `format` passed. @@ -1822,7 +1823,7 @@ console.log(errorMessage); ```cjs console.log( - util.styleText('underline', util.styleText('italic', 'My italic underlined message')), + util.styleText(['underline', 'italic'], 'My italic underlined message'), ); ``` diff --git a/lib/util.js b/lib/util.js index e958f27cd5a1f6..15136c2c6d3ab1 100644 --- a/lib/util.js +++ b/lib/util.js @@ -205,6 +205,22 @@ function pad(n) { */ function styleText(format, text) { validateString(text, 'text'); + + if (ArrayIsArray(format) && format.length > 0) { + let formatCodes = ''; + let append = ''; + for (const f of format) { + const formatCode = inspect.colors[f]; + if (formatCode == null) { + validateOneOf(f, 'format', ObjectKeys(inspect.colors)); + } + formatCodes += `\u001b[${formatCode[0]}m`; + append += `\u001b[${formatCode[1]}m`; + } + + return `${formatCodes}${text}${append}`; + } + const formatCodes = inspect.colors[format]; if (formatCodes == null) { validateOneOf(format, 'format', ObjectKeys(inspect.colors)); diff --git a/test/parallel/test-util-styletext.js b/test/parallel/test-util-styletext.js index 9436133916c58c..261459f1736e95 100644 --- a/test/parallel/test-util-styletext.js +++ b/test/parallel/test-util-styletext.js @@ -33,3 +33,11 @@ assert.throws(() => { }); assert.strictEqual(util.styleText('red', 'test'), '\u001b[31mtest\u001b[39m'); + +assert.strictEqual(util.styleText(['red', 'bold'], 'test'), '\u001b[31m\u001b[1mtest\u001b[39m\u001b[22m'); + +assert.throws(() => { + util.styleText(['invalid'], 'text'); +}, { + code: 'ERR_INVALID_ARG_VALUE', +});