Skip to content

Commit 5c4395b

Browse files
jasnellMylesBorins
authored andcommitted
doc: explain differences in console.assert between node and browsers
Provide an example for implementing browser like behavior for console.assert. This "fixes" #5340 by providing an alternative to changing Node.js' implemented behavior. Instead, we document the differences and show how to work around them if browser like semantics are desired. Fixes: #5340 PR-URL: #6169 Reviewed-By: Robert Jefe Lindstädt <[email protected]> Reviewed-By: Jeff Harris <@techjeffharris>
1 parent 90eb765 commit 5c4395b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

doc/api/console.markdown

+41
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,46 @@ console.assert(false, 'Whoops %s', 'didn\'t work');
109109
// AssertionError: Whoops didn't work
110110
```
111111

112+
*Note: the `console.assert()` method is implemented differently in Node.js
113+
than the `console.assert()` method [available in browsers][web-api-assert].*
114+
115+
Specifically, in browsers, calling `console.assert()` with a falsy
116+
assertion will cause the `message` to be printed to the console without
117+
interrupting execution of subsequent code. In Node.js, however, a falsy
118+
assertion will cause an `AssertionError` to be thrown.
119+
120+
Functionality approximating that implemented by browsers can be implemented
121+
by extending Node.js' `console` and overriding the `console.assert()` method.
122+
123+
In the following example, a simple module is created that extends and overrides
124+
the default behavior of `console` in Node.js.
125+
126+
```js
127+
'use strict';
128+
129+
// Creates a simple extension of console with a
130+
// new impl for assert without monkey-patching.
131+
const myConsole = Object.setPrototypeOf({
132+
assert(assertion, message, ...args) {
133+
try {
134+
console.assert(assertion, message, ...args);
135+
} catch (err) {
136+
console.error(err.stack);
137+
}
138+
}
139+
}, console);
140+
141+
module.exports = myConsole;
142+
```
143+
144+
This can then be used as a direct replacement for the built in console:
145+
146+
```js
147+
const console = require('./myConsole');
148+
console.assert(false, 'this message will print, but no error thrown');
149+
console.log('this will also print');
150+
```
151+
112152
### console.dir(obj[, options])
113153

114154
Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`.
@@ -224,3 +264,4 @@ The `console.warn()` function is an alias for [`console.error()`][].
224264
[`util.format()`]: util.html#util_util_format_format
225265
[`util.inspect()`]: util.html#util_util_inspect_object_options
226266
[customizing `util.inspect()` colors]: util.html#util_customizing_util_inspect_colors
267+
[web-api-assert]: https://developer.mozilla.org/en-US/docs/Web/API/console/assert

0 commit comments

Comments
 (0)