`styleText()` doesn't work within a worker thread
未关闭
还没有人认领这个 Issue。
util
worker
- 主要语言
- JavaScript
- 星标
- 122k
- 派生
- 37.4k
- 平均合并
- 4 天 3 小时
- 30 天内合并 PR
- 272
描述
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
- https://github.com/nodejs/node/blob/main/lib/util.js
- https://github.com/nodejs/node/blob/main/lib/internal/util/colors.js
In chalk, this works out of the box, based on https://github.com/chalk/supports-color
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先复现 worker_threads 示例,然后检查 lib/util.js 和 lib/internal/util/colors.js,报告将它们确定为相关的启发式逻辑。比较主线程和 worker 中的颜色检测,并考虑预期行为中描述的父进程颜色设置。当父进程启用颜色后,styleText() 能够在 worker 中生成预期的彩色输出,即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, nodejs
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 活跃度
- 活跃
- 描述清晰度
- 基本清楚
- 新手友好度
- 68/100