Skip to content

Commit 26f5680

Browse files
authored
WIP: Adding colorText method to util.
1 parent 5a3de82 commit 26f5680

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

lib/util.js

Lines changed: 18 additions & 0 deletions
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,29 @@ 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${txt}\u001b[${formatCodes[1]}m`;
348+
349+
}
350+
334351
// Keep the `exports =` so that various functions can still be monkeypatched
335352
module.exports = {
336353
_errnoException: errnoException,
337354
_exceptionWithHostPort: exceptionWithHostPort,
338355
_extend,
339356
callbackify,
357+
colorText,
340358
debug: debuglog,
341359
debuglog,
342360
deprecate,

test/parallel/test-util-colorText.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
'use strict';
2+
require('../common');
3+
const assert = require('assert');
4+
const util = require('../../lib/util');
5+
const symbol = Symbol('foo');
6+
7+
8+
[
9+
undefined,
10+
null,
11+
false,
12+
5n,
13+
5,
14+
Symbol(),
15+
].forEach((invalidOption) => {
16+
assert.throws(() => {
17+
util.colorText(invalidOption, 'test');
18+
}, {
19+
code: 'ERR_INVALID_ARG_TYPE',
20+
message: /"format" argument must be an string/
21+
});
22+
});

0 commit comments

Comments
 (0)