Skip to content

Commit 5984578

Browse files
util: support array of formats in util.styleText
1 parent 328642b commit 5984578

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

doc/api/util.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1800,7 +1800,8 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
18001800
added: v21.7.0
18011801
-->
18021802
1803-
* `format` {string} A text format defined in `util.inspect.colors`.
1803+
* `format` {string | Array} A text format or an Array
1804+
of text formats defined in `util.inspect.colors`.
18041805
* `text` {string} The text to to be formatted.
18051806
18061807
This function returns a formatted text considering the `format` passed.
@@ -1822,7 +1823,7 @@ console.log(errorMessage);
18221823
18231824
```cjs
18241825
console.log(
1825-
util.styleText('underline', util.styleText('italic', 'My italic underlined message')),
1826+
util.styleText(['underline', 'italic'], 'My italic underlined message'),
18261827
);
18271828
```
18281829

lib/util.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,22 @@ function pad(n) {
205205
*/
206206
function styleText(format, text) {
207207
validateString(text, 'text');
208+
209+
if (ArrayIsArray(format) && format.length > 0) {
210+
let formatCodes = '';
211+
let append = '';
212+
for (const f of format) {
213+
const formatCode = inspect.colors[f];
214+
if (formatCode == null) {
215+
validateOneOf(f, 'format', ObjectKeys(inspect.colors));
216+
}
217+
formatCodes += `\u001b[${formatCode[0]}m`;
218+
append += `\u001b[${formatCode[1]}m`;
219+
}
220+
221+
return `${formatCodes}${text}${append}`;
222+
}
223+
208224
const formatCodes = inspect.colors[format];
209225
if (formatCodes == null) {
210226
validateOneOf(format, 'format', ObjectKeys(inspect.colors));

test/parallel/test-util-styletext.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,11 @@ assert.throws(() => {
3333
});
3434

3535
assert.strictEqual(util.styleText('red', 'test'), '\u001b[31mtest\u001b[39m');
36+
37+
assert.strictEqual(util.styleText(['red', 'bold'], 'test'), '\u001b[31m\u001b[1mtest\u001b[39m\u001b[22m');
38+
39+
assert.throws(() => {
40+
util.styleText(['invalid'], 'text');
41+
}, {
42+
code: 'ERR_INVALID_ARG_VALUE',
43+
});

0 commit comments

Comments
 (0)