Skip to content

Commit 4c5a6c3

Browse files
committed
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
1 parent aba035f commit 4c5a6c3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

doc/api/console.markdown

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,45 @@ console.assert(false, 'Whoops %s', 'didn\'t work');
109109
// AssertionError: Whoops didn't work
110110
```
111111

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

114153
Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`.

0 commit comments

Comments
 (0)