Skip to content

Commit

Permalink
util: adding colorText method
Browse files Browse the repository at this point in the history
  • Loading branch information
hemanth authored Jun 12, 2022
1 parent 5a3de82 commit 9ac1a84
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ const { debuglog } = require('internal/util/debuglog');
const {
validateFunction,
validateNumber,
validateString,
} = require('internal/validators');
const { TextDecoder, TextEncoder } = require('internal/encoding');
const { isBuffer } = require('buffer').Buffer;
Expand Down Expand Up @@ -331,12 +332,28 @@ function getSystemErrorName(err) {
return internalErrorName(err);
}

/**
* @param {string} format
* @param {string} text
* @returns {string}
*/
function colorText(format, text) {
validateString(format, 'format');
validateString(text, 'text');
const formatCodes = inspect.colors[format];
if (!ArrayIsArray(formatCodes)) {
return text;
}
return `\u001b[${formatCodes[0]}m${text}\u001b[${formatCodes[1]}m`;
}

// Keep the `exports =` so that various functions can still be monkeypatched
module.exports = {
_errnoException: errnoException,
_exceptionWithHostPort: exceptionWithHostPort,
_extend,
callbackify,
colorText,
debug: debuglog,
debuglog,
deprecate,
Expand Down
33 changes: 33 additions & 0 deletions test/parallel/test-util-colorText.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';
require('../common');
const assert = require('assert');
const util = require('util');

[
undefined,
null,
false,
5n,
5,
Symbol(),
].forEach((invalidOption) => {
assert.throws(() => {
util.colorText(invalidOption, 'test');
}, {
code: 'ERR_INVALID_ARG_TYPE'
});
assert.throws(() => {
util.colorText('red', invalidOption);
}, {
code: 'ERR_INVALID_ARG_TYPE'
});
});

assert.throws(() => {
util.colorText('red', undefined);
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: 'The "text" argument must be of type string. Received undefined'
});

assert.strictEqual(util.colorText('red', 'test'), '\u001b[31mtest\u001b[39m');

0 comments on commit 9ac1a84

Please sign in to comment.