Node.js Reference ยท Globals and Console
Node.js console.error() and console.warn()
Reference for console.error() and console.warn() in Node.js: writing to stderr, separating errors from output, redirecting streams and logging Error objects.
console.error() and console.warn() work like console.log(), with the same formatting, but they write to standard error (stderr, file descriptor 2) instead of standard output. console.warn() behaves identically.
Keeping messages about problems on stderr means a shell can redirect the two streams separately: node app.js > data.txt saves the real output while errors still appear in the terminal.
console.error('could not open %s', 'config.json');
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
console.error([data[, ...args]]): void console.warn([data[, ...args]]): void
| Name | Description |
|---|---|
data |
The first value; a string may contain %s, %d, %i, %f, %j, %o, %O and %% specifiers. |
...args |
Further values, substituted or appended. |
Returns: undefined.
Edge cases: when stderr is closed or broken, writes can fail with EPIPE as an error event on the stream, which can crash the program if nobody handles it. Node ignores errors from console writes by design, so the call itself does not throw.
Usage notes
- Use stderr for diagnostics, stdout for results. Command-line tools that print data (JSON, CSV) must keep messages out of stdout so other tools can pipe it.
- Passing an
Errorprints its stack, thecausechain and any extra own properties such ascode. That is usually better than loggingerror.messagealone. - No levels or colors.
warnanderrorlook the same. Use a logger when you need severity, timestamps or JSON lines. - Order between stdout and stderr is not guaranteed when both are pipes or redirected to the same file, because they are separate streams.
- Exit codes are unrelated. Logging an error does not change the exit status; set
process.exitCode = 1to signal failure. console.trace()also writes to stderr, and printsTrace:with a stack.- In a test runner stderr output is often shown separately or hidden, so avoid using it for data your assertions need.