diff --git a/lib/util.js b/lib/util.js index fbd8c550318650..f4f7b107639ff6 100644 --- a/lib/util.js +++ b/lib/util.js @@ -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; @@ -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, diff --git a/test/parallel/test-util-colorText.js b/test/parallel/test-util-colorText.js new file mode 100644 index 00000000000000..b23a33e122ad33 --- /dev/null +++ b/test/parallel/test-util-colorText.js @@ -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.equal(util.colorText('red', 'test'), '\u001b[31mtest\u001b[39m');