diff --git a/doc/api/util.md b/doc/api/util.md index bc6eb2182a2981..df6bc4e72a5fbd 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -1831,14 +1831,34 @@ and act according to the configuration set via `NO_COLORS`, ```mjs import { styleText } from 'node:util'; -const errorMessage = styleText('red', 'Error! Error!'); -console.log(errorMessage); +import { stderr } from 'node:process'; + +const successMessage = styleText('green', 'Success!'); +console.log(successMessage); + +const errorMessage = styleText( + 'red', + 'Error! Error!', + // Validate if process.stderr has TTY + { stream: stderr }, +); +console.error(successMessage); ``` ```cjs const { styleText } = require('node:util'); -const errorMessage = styleText('red', 'Error! Error!'); -console.log(errorMessage); +const { stderr } = require('node:process'); + +const successMessage = styleText('green', 'Success!'); +console.log(successMessage); + +const errorMessage = styleText( + 'red', + 'Error! Error!', + // Validate if process.stderr has TTY + { stream: stderr }, +); +console.error(successMessage); ``` `util.inspect.colors` also provides text formats such as `italic`, and diff --git a/lib/util.js b/lib/util.js index 569e539665f56e..59aa4c3ed99d2e 100644 --- a/lib/util.js +++ b/lib/util.js @@ -56,11 +56,17 @@ const { } = require('internal/util/inspect'); const { debuglog } = require('internal/util/debuglog'); const { + validateBoolean, validateFunction, validateNumber, validateString, validateOneOf, } = require('internal/validators'); +const { + isReadableStream, + isWritableStream, + isNodeStream, +} = require('internal/streams/utils'); const types = require('internal/util/types'); let utilColors; @@ -106,8 +112,17 @@ function escapeStyleCode(code) { */ function styleText(format, text, { validateStream = true, stream = process.stdout } = {}) { validateString(text, 'text'); + validateBoolean(validateStream, 'options.validateStream'); if (validateStream) { + if ( + !isReadableStream(stream) && + !isWritableStream(stream) && + !isNodeStream(stream) + ) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream); + } + if ( !stream || !lazyUtilColors().shouldColorize(stream) diff --git a/test/parallel/test-util-styletext.js b/test/parallel/test-util-styletext.js index 9bb8cbd04ac43d..ddb99c57184c7a 100644 --- a/test/parallel/test-util-styletext.js +++ b/test/parallel/test-util-styletext.js @@ -50,6 +50,15 @@ assert.throws(() => { code: 'ERR_INVALID_ARG_VALUE', }); +assert.throws(() => { + util.styleText('red', 'text', { stream: {} }); +}, { + code: 'ERR_INVALID_ARG_TYPE', +}); + +// does not throw +util.styleText('red', 'text', { stream: {}, validateStream: false }); + assert.strictEqual(util.styleText('red', 'test'), styled); const originalEnv = process.env;