File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -64,6 +64,7 @@ const { debuglog } = require('internal/util/debuglog');
6464const {
6565 validateFunction,
6666 validateNumber,
67+ validateString
6768} = require ( 'internal/validators' ) ;
6869const { TextDecoder, TextEncoder } = require ( 'internal/encoding' ) ;
6970const { 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
335352module . exports = {
336353 _errnoException : errnoException ,
337354 _exceptionWithHostPort : exceptionWithHostPort ,
338355 _extend,
339356 callbackify,
357+ colorText,
340358 debug : debuglog ,
341359 debuglog,
342360 deprecate,
Original file line number Diff line number Diff line change 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 : / " f o r m a t " a r g u m e n t m u s t b e a n s t r i n g /
21+ } ) ;
22+ } ) ;
You can’t perform that action at this time.
0 commit comments