Skip to content

Commit

Permalink
WIP: Adding colorText method to util.
Browse files Browse the repository at this point in the history
  • Loading branch information
hemanth authored Jun 10, 2022
1 parent 5a3de82 commit 26f5680
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
18 changes: 18 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,29 @@ 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${txt}\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
22 changes: 22 additions & 0 deletions test/parallel/test-util-colorText.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';
require('../common');
const assert = require('assert');
const util = require('../../lib/util');
const symbol = Symbol('foo');


[
undefined,
null,
false,
5n,
5,
Symbol(),
].forEach((invalidOption) => {
assert.throws(() => {
util.colorText(invalidOption, 'test');
}, {
code: 'ERR_INVALID_ARG_TYPE',
message: /"format" argument must be an string/
});
});

0 comments on commit 26f5680

Please sign in to comment.