Skip to content

Commit 9c94ffe

Browse files
authoredJun 11, 2022
util: adding colorText method
1 parent 5a3de82 commit 9c94ffe

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
 

‎lib/util.js

+17
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ const { debuglog } = require('internal/util/debuglog');
6464
const {
6565
validateFunction,
6666
validateNumber,
67+
validateString,
6768
} = require('internal/validators');
6869
const { TextDecoder, TextEncoder } = require('internal/encoding');
6970
const { isBuffer } = require('buffer').Buffer;
@@ -331,12 +332,28 @@ function getSystemErrorName(err) {
331332
return internalErrorName(err);
332333
}
333334

335+
/**
336+
* @param {string} format
337+
* @param {string} text
338+
* @returns {string}
339+
*/
340+
function colorText(format, text) {
341+
validateString(format, 'format');
342+
validateString(text, 'text');
343+
const formatCodes = inspect.colors[format];
344+
if (!ArrayIsArray(formatCodes)) {
345+
return text;
346+
}
347+
return `\u001b[${formatCodes[0]}m${text}\u001b[${formatCodes[1]}m`;
348+
}
349+
334350
// Keep the `exports =` so that various functions can still be monkeypatched
335351
module.exports = {
336352
_errnoException: errnoException,
337353
_exceptionWithHostPort: exceptionWithHostPort,
338354
_extend,
339355
callbackify,
356+
colorText,
340357
debug: debuglog,
341358
debuglog,
342359
deprecate,

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

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use strict';
2+
require('../common');
3+
const assert = require('assert');
4+
const util = require('util');
5+
6+
[
7+
undefined,
8+
null,
9+
false,
10+
5n,
11+
5,
12+
Symbol(),
13+
].forEach((invalidOption) => {
14+
assert.throws(() => {
15+
util.colorText(invalidOption, 'test');
16+
}, {
17+
code: 'ERR_INVALID_ARG_TYPE'
18+
});
19+
assert.throws(() => {
20+
util.colorText('red', invalidOption);
21+
}, {
22+
code: 'ERR_INVALID_ARG_TYPE'
23+
});
24+
});
25+
26+
assert.throws(() => {
27+
util.colorText('red', undefined);
28+
}, {
29+
code: 'ERR_INVALID_ARG_TYPE',
30+
message: 'The "text" argument must be of type string. Received undefined'
31+
});
32+
33+
assert.equal(util.colorText('red', 'test'), '\u001b[31mtest\u001b[39m');

0 commit comments

Comments
 (0)