Skip to content

styleText() doesn't work within a worker thread #65766

Description

@slorber

Version

26.8.1

Platform

Darwin MacBook-Pro-de-Sebastien.local 24.6.0 Darwin Kernel Version 24.6.0: Tue Apr 21 20:16:56 PDT 2026; root:xnu-11417.140.69.710.16~1/RELEASE_ARM64_T6030 arm64

Subsystem

No response

What steps will reproduce the bug?

const {Worker} = require('node:worker_threads');
const {styleText} = require('node:util');
const tty = require('node:tty');

console.log('MAIN', {
  isTTY: process.stdout.isTTY,
  isatty: tty.isatty(1),
  styled: JSON.stringify(styleText('red', 'hello')),
});

await new Promise((resolve, reject) => {
  const worker = new Worker(`
    const {parentPort} = require('node:worker_threads');
    const {styleText} = require('node:util');
    const tty = require('node:tty');

    parentPort.postMessage({
      isTTY: process.stdout.isTTY,
      isatty: tty.isatty(1),
      styled: JSON.stringify(styleText('red', 'hello')),
    });
  `, {eval: true});

  worker.on('message', msg => {
    console.log('WORKER', msg);
    resolve();
  });

  worker.on('error', reject);
});

Output:

MAIN {
  isTTY: true,
  isatty: true,
  styled: '"\\u001b[31mhello\\u001b[39m"'
}

WORKER {
  isTTY: undefined,
  isatty: true,
  styled: '"hello"'
}

Even simpler repro:

const { Worker } = require('node:worker_threads');
const { styleText } = require('node:util');

console.log('main:', styleText('red', 'hello'));

new Worker(`
  const { styleText } = require('node:util');

  console.log('worker:', styleText('red', 'hello'));
`, { eval: true });

How often does it reproduce? Is there a required condition?

constantly

What is the expected behavior? Why is that the expected behavior?

I think it's reasonable to expect styleText() to also work in worker threads by default if the parent has colors enabled. I'd rather have an opt-out than an opt-in through worker thread config/env.

What do you see instead?

The worker thread

Additional information

From what I understand, the heuristic used in styleText() is too limited and could be improved to support colors in worker threads better

In chalk, this works out of the box, based on https://github.com/chalk/supports-color

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    utilIssues and PRs related to the built-in util module.workerIssues and PRs related to the worker_threads module and Worker API.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions