Node.js on Windows: console color output showing escape sequences not colors

  ansi-escape, console, node.js, windows

Node.js by default uses escape sequences to color various kinds of output, such as error messages. On my Windows 10 system, this is in some circumstances not working:

C:t>type a.js

C:t>node a.js

ReferenceError: x is not defined
    at Object.<anonymous> (C:ta.js:1:13)
[90m    at Module._compile (internal/modules/cjs/loader.js:1063:30)[39m
[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)[39m
[90m    at Module.load (internal/modules/cjs/loader.js:928:32)[39m
[90m    at Function.Module._load (internal/modules/cjs/loader.js:769:14)[39m
[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m
[90m    at internal/main/run_main_module.js:17:47[39m

(Most of the above lines begin with a question mark in a square, then open square bracket, then 90m, obviously an escape sequence being rendered literally rather than interpreted.)

It might be tempting to conclude that my Windows console somehow got broken, but color output works for other things, like git and ripgrep, and even Node in repl mode:

Welcome to Node.js v14.16.1.
Type ".help" for more information.
> console.trace(99)
Trace: 99
    at REPL7:1:9
    at Script.runInThisContext (vm.js:133:18)
    at REPLServer.defaultEval (repl.js:484:29)
    at bound (domain.js:413:15)
    at REPLServer.runBound [as eval] (domain.js:424:12)
    at REPLServer.onLine (repl.js:817:10)
    at REPLServer.emit (events.js:327:22)
    at REPLServer.EventEmitter.emit (domain.js:467:12)
    at REPLServer.Interface._onLine (readline.js:337:10)
    at REPLServer.Interface._line (readline.js:666:8)

No literally rendered escape sequences in the above; 99 is colored yellow and undefined is colored dark gray. So the capability does exist at some level; it’s just not being activated correctly.

What’s going wrong, and what’s the best way to fix it?

Source: Windows Questions