Skip to content

Commit e79791f

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

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

doc/api/util.md

+12-2
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,16 @@ 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'),
1827+
);
1828+
```
1829+
1830+
When passing an array of formats, the order of the format applied
1831+
is left to right so the following style might overwrite the previous one.
1832+
1833+
```cjs
1834+
console.log(
1835+
util.styleText(['red', 'green'], 'text'), // green
18261836
);
18271837
```
18281838

lib/util.js

+16
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${append}`;
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

+9
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,12 @@ assert.throws(() => {
3333
});
3434

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

0 commit comments

Comments
 (0)