-
-
Notifications
You must be signed in to change notification settings - Fork 32.8k
console: do not emit error events #9744
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
299f647
to
e0c476d
Compare
lib/console.js
Outdated
if (err) { | ||
stream.once('error', () => {}); | ||
} | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this 'error' function is added over and over again at every write.
I think the function should be added after stream.write synchronously, and then removed in the callback.
Beware of not allocating any new callbacks here, we will be adding strain to the gc for nothing (they can all be top level).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
'error' function is added over and over again at every write.
Only if it fails? Like, maybe there’s a performance impact, but only in situations where the process current emits an uncaught exception.
I think the function should be added after stream.write synchronously, and then removed in the callback.
The error event is emitted after the callback, so I don’t think that works.
Beware of not allocating any new callbacks here, we will be adding strain to the gc for nothing (they can all be top level).
Done, thanks for pointing that out.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The error event is emitted after the callback, so I don’t think that works.
Then this PR creates a memory leak, and after a single console.log
is used, any 'error'
event will be swallowed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@mcollina This is .once
, not .on
? If the callback sees an err
argument, then that error will be emitted as an 'error'
event, so the extra listener will be called and removed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ooh, I did not notice, sorry. Add a comment there, so it's easy to understand what's going on.
e0c476d
to
b04283b
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM if CI is green.
Some comments needed to explain what's going on.
Added a bit of text for clarification. |
Previous related discussion at #9470 I'll take a look soon but this will also necessitate |
That would make it admittedly less browser-like but browser conformity wasn't why I revived this in the first place. |
@Fishrock123 I’m not sure how I feel about that yet, but notice how this change could also be applied as an/in an userland module. I assume the set of packages (like progress bars) which want a “safe” behaviour is quite overseeable? |
You can already do this in userland by just adding an error handler to stdio streams. The point is that it would be by default. |
@Fishrock123 I've always used direct Maybe those are two separate things, aren't they? |
lib/console.js
Outdated
// an `error` event. Adding a `once` listener will keep that error | ||
// from becoming an uncaught exception, but since the handler is | ||
// removed after the event, non-console.* writes won’t be affected. | ||
stream.once('error', noop); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
hmm... can we guarantee this? For instance, if the callback ends up getting deferred by some buffering thing and some other error occurs that consumes the noop handler here....
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Lines 338 to 347 in 0a265df
function onwriteError(stream, state, sync, er, cb) { | |
--state.pendingcb; | |
if (sync) | |
process.nextTick(cb, er); | |
else | |
cb(er); | |
stream._writableState.errorEmitted = true; | |
stream.emit('error', er); | |
} |
(update: fixed link)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@addaleax, technically @jasnell has a point. You will need to wrap write
in a once
and removeListener
pair : in https://github.com/nodejs/node/blob/master/lib/_stream_writable.js#L340-L346, if sync
is true the error is emitted before, then after.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ugh right, thanks for pointing out the “right” solution for this… updated and added tests for both scenarios
PTAL
lib/console.js
Outdated
// an `error` event. Adding a `once` listener will keep that error | ||
// from becoming an uncaught exception, but since the handler is | ||
// removed after the event, non-console.* writes won’t be affected. | ||
stream.once('error', noop); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@addaleax, technically @jasnell has a point. You will need to wrap write
in a once
and removeListener
pair : in https://github.com/nodejs/node/blob/master/lib/_stream_writable.js#L340-L346, if sync
is true the error is emitted before, then after.
e883c56
to
1e4f914
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM if CI is green
@Fishrock123 Since you assigned this to yourself… what are the things you’d like to see/talk about here? |
ping @Fishrock123 ? |
@Fishrock123 It’s been a while… unless there are any objections, I’d like to land this in the next couple of days. |
lib/console.js
Outdated
// Add and later remove a noop error handler to catch synchronous errors. | ||
stream.once('error', noop); | ||
|
||
stream.write(string, (err) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Rather than allocating a closure here, can this be made a top level function?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It can’t be top-level because it still needs access to the stream but I’ve attached these to the console object itself, does that work for you? It definitely avoids the closure problem.
lib/console.js
Outdated
} catch (e) { | ||
// Sorry, there’s no proper way to pass along the error here. | ||
} finally { | ||
stream.removeListener('error', noop); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm... going back to the earlier point, is the write operation guaranteed to be complete by the time we hit this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No but that’s not a problem. Asynchronous errors are handled from inside the callback.
@@ -0,0 +1,17 @@ | |||
'use strict'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be helpful to have additional tests that verify this works with a variety of stdout/stderr configurations (e.g. stdio as a file, stdio as a pipe, etc)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’ve updated this with tests for something that errors asynchronously… the inner workings of console aren’t really tied to I/O at all, so I’m not sure it makes sense to add explicit tests for these
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The main thing that I'm hoping for is that this would fix the issue reported in #831
1e4f914
to
9bc88af
Compare
@jasnell please take another look when you have the time :) |
Reviewing now... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A minor nit but generally LGTM
const assert = require('assert'); | ||
|
||
const out = new Writable({ | ||
write(chunk, enc, callback) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just to be on the safe side, there should likely be a check that verifies this version of write
is being called. I'm not certain if common.mustCall()
would work here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jasnell Done, good point. (Sorry for being late, must have overlooked your replies.)
Fixes: nodejs#831 Fixes: nodejs#947 Ref: nodejs#9470
Still LGTM and +1 to semver-major |
Landed in f18e08d |
Fixes: #831 Fixes: #947 Ref: #9470 PR-URL: #9744 Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]>
I still hold that this requires us to implement a |
@Fishrock123 Sorry, what exactly are you suggesting? |
I will make a PR shortly. (hopefully) |
Apply the `console: do not emit error events` changes properly to `console.dir()`. This was overlooked in f18e08d (nodejs#9744). Ref: nodejs@f18e08d#commitcomment-20934407
Apply the `console: do not emit error events` changes properly to `console.dir()`. This was overlooked in f18e08d (#9744). Ref: f18e08d#commitcomment-20934407 PR-URL: #11443 Reviewed-By: James M Snell <[email protected]>
* **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](nodejs@4a7233c178)] [nodejs#12892](nodejs#12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](nodejs@d2d32ea5a2)] [nodejs#11968](nodejs#11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](nodejs@7eb1b4658e)] [nodejs#12141](nodejs#12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](nodejs@beca3244e2)] [nodejs#10236](nodejs#10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](nodejs@97a77288ce)] [nodejs#12348](nodejs#12348), [[`d75fdd96aa`](nodejs@d75fdd96aa)] [nodejs#10423](nodejs#10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](nodejs@627ecee9ed)] [nodejs#10653](nodejs#10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](nodejs@f18e08d820)] [nodejs#9744](nodejs#9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](nodejs@3c3b36af0f)] [nodejs#12936](nodejs#12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](nodejs@60d1aac8d2)] [nodejs#12784](nodejs#12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](nodejs@84dabe8373)] [nodejs#12489](nodejs#12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](nodejs@7a55e34ef4)] [nodejs#10467](nodejs#10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](nodejs@3c2a9361ff)] [nodejs#9683](nodejs#9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](nodejs@90403dd1d0)] [nodejs#11567](nodejs#11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](nodejs@d3480776c7)] [nodejs#11259](nodejs#11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](nodejs@fb71ba4921)] [nodejs#11355](nodejs#11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](nodejs@3e6f1032a4)] [nodejs#10805](nodejs#10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](nodejs@5de3cf099c)] [nodejs#10116](nodejs#10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](nodejs@84a23391f6)] [nodejs#12113](nodejs#12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](nodejs@56e881d0b0)] [nodejs#11975](nodejs#11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](nodejs@03e89b3ff2)] [nodejs#10116](nodejs#10116). * Process warnings may now include additional detail [[`dd20e68b0f`](nodejs@dd20e68b0f)] [nodejs#12725](nodejs#12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](nodejs@3f27f02da0)] [nodejs#11599](nodejs#11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (nodejs@ec7cbaf266)] [nodejs#12995](nodejs#12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](nodejs@a16b570f8c)] [nodejs#11968](nodejs#11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](nodejs@010f864426)] [nodejs#12949](nodejs#12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](nodejs@a5f91ab230)] [nodejs#11689](nodejs#11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](nodejs@8a7db9d4b5)] [nodejs#12087](nodejs#12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](nodejs@b6e1d22fa6)] [nodejs#12925](nodejs#12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](nodejs@07c7f198db)] [nodejs#12828](nodejs#12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](nodejs@348cc80a3c)] [nodejs#5923](nodejs#5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](nodejs@a2ae08999b)] [nodejs#11349](nodejs#11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](nodejs@d523eb9c40)] [nodejs#11447](nodejs#11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](nodejs@d080ead0f9)] [nodejs#12710](nodejs#12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](nodejs@5bfd13b81e)] [nodejs#9726](nodejs#9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](nodejs@455e6f1dd8)] [nodejs#11708](nodejs#11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](nodejs@aab0d202f8)] [nodejs#11624](nodejs#11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](nodejs@99da8e8e02)] [nodejs#12442](nodejs#12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](nodejs@91383e47fd)] [nodejs#12001](nodejs#12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](nodejs@b514bd231e)] [nodejs#11391](nodejs#11391).
* **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](4a7233c178)] [#12892](#12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](d2d32ea5a2)] [#11968](#11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](7eb1b4658e)] [#12141](#12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](beca3244e2)] [#10236](#10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](97a77288ce)] [#12348](#12348), [[`d75fdd96aa`](d75fdd96aa)] [#10423](#10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](627ecee9ed)] [#10653](#10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](f18e08d820)] [#9744](#9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](3c3b36af0f)] [#12936](#12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](60d1aac8d2)] [#12784](#12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](84dabe8373)] [#12489](#12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](7a55e34ef4)] [#10467](#10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](3c2a9361ff)] [#9683](#9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](90403dd1d0)] [#11567](#11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](d3480776c7)] [#11259](#11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](fb71ba4921)] [#11355](#11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](3e6f1032a4)] [#10805](#10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](5de3cf099c)] [#10116](#10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](84a23391f6)] [#12113](#12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](56e881d0b0)] [#11975](#11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](03e89b3ff2)] [#10116](#10116). * Process warnings may now include additional detail [[`dd20e68b0f`](dd20e68b0f)] [#12725](#12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](3f27f02da0)] [#11599](#11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (ec7cbaf266)] [#12995](#12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](a16b570f8c)] [#11968](#11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](010f864426)] [#12949](#12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](a5f91ab230)] [#11689](#11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](8a7db9d4b5)] [#12087](#12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](b6e1d22fa6)] [#12925](#12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](07c7f198db)] [#12828](#12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](348cc80a3c)] [#5923](#5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](a2ae08999b)] [#11349](#11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](d523eb9c40)] [#11447](#11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](d080ead0f9)] [#12710](#12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](5bfd13b81e)] [#9726](#9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](455e6f1dd8)] [#11708](#11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](aab0d202f8)] [#11624](#11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](99da8e8e02)] [#12442](#12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](91383e47fd)] [#12001](#12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](b514bd231e)] [#11391](#11391).
* **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](4a7233c178)] [#12892](#12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](d2d32ea5a2)] [#11968](#11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](7eb1b4658e)] [#12141](#12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](beca3244e2)] [#10236](#10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](97a77288ce)] [#12348](#12348), [[`d75fdd96aa`](d75fdd96aa)] [#10423](#10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](627ecee9ed)] [#10653](#10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](f18e08d820)] [#9744](#9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](3c3b36af0f)] [#12936](#12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](60d1aac8d2)] [#12784](#12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](84dabe8373)] [#12489](#12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](7a55e34ef4)] [#10467](#10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](3c2a9361ff)] [#9683](#9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](90403dd1d0)] [#11567](#11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](d3480776c7)] [#11259](#11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](fb71ba4921)] [#11355](#11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](3e6f1032a4)] [#10805](#10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](5de3cf099c)] [#10116](#10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](84a23391f6)] [#12113](#12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](56e881d0b0)] [#11975](#11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](03e89b3ff2)] [#10116](#10116). * Process warnings may now include additional detail [[`dd20e68b0f`](dd20e68b0f)] [#12725](#12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](3f27f02da0)] [#11599](#11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (ec7cbaf266)] [#12995](#12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](a16b570f8c)] [#11968](#11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](010f864426)] [#12949](#12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](a5f91ab230)] [#11689](#11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](8a7db9d4b5)] [#12087](#12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](b6e1d22fa6)] [#12925](#12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](07c7f198db)] [#12828](#12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](348cc80a3c)] [#5923](#5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](a2ae08999b)] [#11349](#11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](d523eb9c40)] [#11447](#11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](d080ead0f9)] [#12710](#12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](5bfd13b81e)] [#9726](#9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](455e6f1dd8)] [#11708](#11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](aab0d202f8)] [#11624](#11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](99da8e8e02)] [#12442](#12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](91383e47fd)] [#12001](#12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](b514bd231e)] [#11391](#11391).
# Console <!--introduced_in=v0.10.13--> > Stability: 2 - Stable <!-- source_link=lib/console.js --> The `node:console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`][] and [`process.stderr`][]. The global `console` can be used without calling `require('node:console')`. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. Programs that desire to depend on the synchronous / asynchronous behavior of the console functions should first figure out the nature of console's backing stream. This is because the stream is dependent on the underlying platform and standard stream configuration of the current process. See the [note on process I/O][] for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ``` ## Class: `Console` <!-- YAML changes: - version: v8.0.0 pr-url: nodejs#9744 description: Errors that occur while writing to the underlying streams will now be ignored by default. --> <!--type=class--> The `Console` class can be used to create a simple logger with configurable output streams and can be accessed using either `require('node:console').Console` or `console.Console` (or their destructured counterparts): ```mjs import { Console } from 'node:console'; ``` ```cjs const { Console } = require('node:console'); ``` ```js const { Console } = console; ``` ### `new Console(stdout[, stderr][, ignoreErrors])` ### `new Console(options)` <!-- YAML changes: - version: - v14.2.0 - v12.17.0 pr-url: nodejs#32964 description: The `groupIndentation` option was introduced. - version: v11.7.0 pr-url: nodejs#24978 description: The `inspectOptions` option is introduced. - version: v10.0.0 pr-url: nodejs#19372 description: The `Console` constructor now supports an `options` argument, and the `colorMode` option was introduced. - version: v8.0.0 pr-url: nodejs#9744 description: The `ignoreErrors` option was introduced. --> * `options` {Object} * `stdout` {stream.Writable} * `stderr` {stream.Writable} * `ignoreErrors` {boolean} Ignore errors when writing to the underlying streams. **Default:** `true`. * `colorMode` {boolean|string} Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well. **Default:** `'auto'`. * `inspectOptions` {Object} Specifies options that are passed along to [`util.inspect()`][]. * `groupIndentation` {number} Set group indentation. **Default:** `2`. Creates a new `Console` with one or two writable stream instances. `stdout` is a writable stream to print log or info output. `stderr` is used for warning or error output. If `stderr` is not provided, `stdout` is used for `stderr`. ```mjs import { createWriteStream } from 'node:fs'; import { Console } from 'node:console'; // Alternatively // const { Console } = console; const output = createWriteStream('./stdout.log'); const errorOutput = createWriteStream('./stderr.log'); // Custom simple logger const logger = new Console({ stdout: output, stderr: errorOutput }); // use it like console const count = 5; logger.log('count: %d', count); // In stdout.log: count 5 ``` ```cjs const fs = require('node:fs'); const { Console } = require('node:console'); // Alternatively // const { Console } = console; const output = fs.createWriteStream('./stdout.log'); const errorOutput = fs.createWriteStream('./stderr.log'); // Custom simple logger const logger = new Console({ stdout: output, stderr: errorOutput }); // use it like console const count = 5; logger.log('count: %d', count); // In stdout.log: count 5 ``` The global `console` is a special `Console` whose output is sent to [`process.stdout`][] and [`process.stderr`][]. It is equivalent to calling: ```js new Console({ stdout: process.stdout, stderr: process.stderr }); ``` ### `console.assert(value[, ...message])` <!-- YAML added: v0.1.101 changes: - version: v10.0.0 pr-url: nodejs#17706 description: The implementation is now spec compliant and does not throw anymore. --> * `value` {any} The value tested for being truthy. * `...message` {any} All arguments besides `value` are used as error message. `console.assert()` writes a message if `value` is [falsy][] or omitted. It only writes a message and does not otherwise affect execution. The output always starts with `"Assertion failed"`. If provided, `message` is formatted using [`util.format()`][]. If `value` is [truthy][], nothing happens. ```js console.assert(true, 'does nothing'); console.assert(false, 'Whoops %s work', 'didn\'t'); // Assertion failed: Whoops didn't work console.assert(); // Assertion failed ``` ### `console.clear()` <!-- YAML added: v8.3.0 --> When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. When `stdout` is not a TTY, this method does nothing. The specific operation of `console.clear()` can vary across operating systems and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the current terminal viewport for the Node.js binary. ### `console.count([label])` <!-- YAML added: v8.3.0 --> * `label` {string} The display label for the counter. **Default:** `'default'`. Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. <!-- eslint-skip --> ```js > console.count() default: 1 undefined > console.count('default') default: 2 undefined > console.count('abc') abc: 1 undefined > console.count('xyz') xyz: 1 undefined > console.count('abc') abc: 2 undefined > console.count() default: 3 undefined > ``` ### `console.countReset([label])` <!-- YAML added: v8.3.0 --> * `label` {string} The display label for the counter. **Default:** `'default'`. Resets the internal counter specific to `label`. <!-- eslint-skip --> ```js > console.count('abc'); abc: 1 undefined > console.countReset('abc'); undefined > console.count('abc'); abc: 1 undefined > ``` ### `console.debug(data[, ...args])` <!-- YAML added: v8.0.0 changes: - version: v8.10.0 pr-url: nodejs#17033 description: "`console.debug` is now an alias for `console.log`." --> * `data` {any} * `...args` {any} The `console.debug()` function is an alias for [`console.log()`][]. ### `console.dir(obj[, options])` <!-- YAML added: v0.1.101 --> * `obj` {any} * `options` {Object} * `showHidden` {boolean} If `true` then the object's non-enumerable and symbol properties will be shown too. **Default:** `false`. * `depth` {number} Tells [`util.inspect()`][] how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`. **Default:** `2`. * `colors` {boolean} If `true`, then the output will be styled with ANSI color codes. Colors are customizable; see [customizing `util.inspect()` colors][]. **Default:** `false`. Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`. This function bypasses any custom `inspect()` function defined on `obj`. ### `console.dirxml(...data)` <!-- YAML added: v8.0.0 changes: - version: v9.3.0 pr-url: nodejs#17152 description: "`console.dirxml` now calls `console.log` for its arguments." --> * `...data` {any} This method calls `console.log()` passing it the arguments received. This method does not produce any XML formatting. ### `console.error([data][, ...args])` <!-- YAML added: v0.1.100 --> * `data` {any} * `...args` {any} Prints to `stderr` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to [`util.format()`][]). ```js const code = 5; console.error('error #%d', code); // Prints: error nodejs#5, to stderr console.error('error', code); // Prints: error 5, to stderr ``` If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`][] is called on each argument and the resulting string values are concatenated. See [`util.format()`][] for more information. ### `console.group([...label])` <!-- YAML added: v8.5.0 --> * `...label` {any} Increases indentation of subsequent lines by spaces for `groupIndentation` length. If one or more `label`s are provided, those are printed first without the additional indentation. ### `console.groupCollapsed()` <!-- YAML added: v8.5.0 --> An alias for [`console.group()`][]. ### `console.groupEnd()` <!-- YAML added: v8.5.0 --> Decreases indentation of subsequent lines by spaces for `groupIndentation` length. ### `console.info([data][, ...args])` <!-- YAML added: v0.1.100 --> * `data` {any} * `...args` {any} The `console.info()` function is an alias for [`console.log()`][]. ### `console.log([data][, ...args])` <!-- YAML added: v0.1.100 --> * `data` {any} * `...args` {any} Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to [`util.format()`][]). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`][] for more information. ### `console.table(tabularData[, properties])` <!-- YAML added: v10.0.0 --> * `tabularData` {any} * `properties` {string\[]} Alternate properties for constructing the table. Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just logging the argument if it can't be parsed as tabular. ```js // These can't be parsed as tabular data console.table(Symbol()); // Symbol() console.table(undefined); // undefined console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); // ┌─────────┬─────┬─────┐ // │ (index) │ a │ b │ // ├─────────┼─────┼─────┤ // │ 0 │ 1 │ 'Y' │ // │ 1 │ 'Z' │ 2 │ // └─────────┴─────┴─────┘ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); // ┌─────────┬─────┐ // │ (index) │ a │ // ├─────────┼─────┤ // │ 0 │ 1 │ // │ 1 │ 'Z' │ // └─────────┴─────┘ ``` ### `console.time([label])` <!-- YAML added: v0.1.104 --> * `label` {string} **Default:** `'default'` Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. Use the same `label` when calling [`console.timeEnd()`][] to stop the timer and output the elapsed time in suitable time units to `stdout`. For example, if the elapsed time is 3869ms, `console.timeEnd()` displays "3.869s". ### `console.timeEnd([label])` <!-- YAML added: v0.1.104 changes: - version: v13.0.0 pr-url: nodejs#29251 description: The elapsed time is displayed with a suitable time unit. - version: v6.0.0 pr-url: nodejs#5901 description: This method no longer supports multiple calls that don't map to individual `console.time()` calls; see below for details. --> * `label` {string} **Default:** `'default'` Stops a timer that was previously started by calling [`console.time()`][] and prints the result to `stdout`: ```js console.time('bunch-of-stuff'); // Do a bunch of stuff. console.timeEnd('bunch-of-stuff'); // Prints: bunch-of-stuff: 225.438ms ``` ### `console.timeLog([label][, ...data])` <!-- YAML added: v10.7.0 --> * `label` {string} **Default:** `'default'` * `...data` {any} For a timer that was previously started by calling [`console.time()`][], prints the elapsed time and other `data` arguments to `stdout`: ```js console.time('process'); const value = expensiveProcess1(); // Returns 42 console.timeLog('process', value); // Prints "process: 365.227ms 42". doExpensiveProcess2(value); console.timeEnd('process'); ``` ### `console.trace([message][, ...args])` <!-- YAML added: v0.1.104 --> * `message` {any} * `...args` {any} Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`][] formatted message and stack trace to the current position in the code. ```js console.trace('Show me'); // Prints: (stack trace will vary based on where trace is called) // Trace: Show me // at repl:2:9 // at REPLServer.defaultEval (repl.js:248:27) // at bound (domain.js:287:14) // at REPLServer.runBound [as eval] (domain.js:300:12) // at REPLServer.<anonymous> (repl.js:412:12) // at emitOne (events.js:82:20) // at REPLServer.emit (events.js:169:7) // at REPLServer.Interface._onLine (readline.js:210:10) // at REPLServer.Interface._line (readline.js:549:8) // at REPLServer.Interface._ttyWrite (readline.js:826:14) ``` ### `console.warn([data][, ...args])` <!-- YAML added: v0.1.100 --> * `data` {any} * `...args` {any} The `console.warn()` function is an alias for [`console.error()`][]. ## Inspector only methods The following methods are exposed by the V8 engine in the general API but do not display anything unless used in conjunction with the [inspector][] (`--inspect` flag). ### `console.profile([label])` <!-- YAML added: v8.0.0 --> * `label` {string} This method does not display anything unless used in the inspector. The `console.profile()` method starts a JavaScript CPU profile with an optional label until [`console.profileEnd()`][] is called. The profile is then added to the **Profile** panel of the inspector. ```js console.profile('MyLabel'); // Some code console.profileEnd('MyLabel'); // Adds the profile 'MyLabel' to the Profiles panel of the inspector. ``` ### `console.profileEnd([label])` <!-- YAML added: v8.0.0 --> * `label` {string} This method does not display anything unless used in the inspector. Stops the current JavaScript CPU profiling session if one has been started and prints the report to the **Profiles** panel of the inspector. See [`console.profile()`][] for an example. If this method is called without a label, the most recently started profile is stopped. ### `console.timeStamp([label])` <!-- YAML added: v8.0.0 --> * `label` {string} This method does not display anything unless used in the inspector. The `console.timeStamp()` method adds an event with the label `'label'` to the **Timeline** panel of the inspector. [`console.error()`]: #consoleerrordata-args [`console.group()`]: #consolegrouplabel [`console.log()`]: #consolelogdata-args [`console.profile()`]: #consoleprofilelabel [`console.profileEnd()`]: #consoleprofileendlabel [`console.time()`]: #consoletimelabel [`console.timeEnd()`]: #consoletimeendlabel [`process.stderr`]: process.md#processstderr [`process.stdout`]: process.md#processstdout [`util.format()`]: util.md#utilformatformat-args [`util.inspect()`]: util.md#utilinspectobject-options [customizing `util.inspect()` colors]: util.md#customizing-utilinspect-colors [falsy]: https://developer.mozilla.org/en-US/docs/Glossary/Falsy [inspector]: debugger.md [note on process I/O]: process.md#a-note-on-process-io [truthy]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
Checklist
make -j8 test
(UNIX), orvcbuild test nosign
(Windows) passesAffected core subsystem(s)
console
Description of change
Never fail for streams errors resulting from the
console.*
methods.I know relatively little about the backstory here, so feel free to shoot this down quickly if it’s already been discussed and discarded.
/cc @Fishrock123