• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Console
2
3<!--introduced_in=v0.10.13-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/console.js -->
8
9The `node:console` module provides a simple debugging console that is similar to
10the JavaScript console mechanism provided by web browsers.
11
12The module exports two specific components:
13
14* A `Console` class with methods such as `console.log()`, `console.error()`, and
15  `console.warn()` that can be used to write to any Node.js stream.
16* A global `console` instance configured to write to [`process.stdout`][] and
17  [`process.stderr`][]. The global `console` can be used without calling
18  `require('node:console')`.
19
20_**Warning**_: The global console object's methods are neither consistently
21synchronous like the browser APIs they resemble, nor are they consistently
22asynchronous like all other Node.js streams. See the [note on process I/O][] for
23more information.
24
25Example using the global `console`:
26
27```js
28console.log('hello world');
29// Prints: hello world, to stdout
30console.log('hello %s', 'world');
31// Prints: hello world, to stdout
32console.error(new Error('Whoops, something bad happened'));
33// Prints error message and stack trace to stderr:
34//   Error: Whoops, something bad happened
35//     at [eval]:5:15
36//     at Script.runInThisContext (node:vm:132:18)
37//     at Object.runInThisContext (node:vm:309:38)
38//     at node:internal/process/execution:77:19
39//     at [eval]-wrapper:6:22
40//     at evalScript (node:internal/process/execution:76:60)
41//     at node:internal/main/eval_string:23:3
42
43const name = 'Will Robinson';
44console.warn(`Danger ${name}! Danger!`);
45// Prints: Danger Will Robinson! Danger!, to stderr
46```
47
48Example using the `Console` class:
49
50```js
51const out = getStreamSomehow();
52const err = getStreamSomehow();
53const myConsole = new console.Console(out, err);
54
55myConsole.log('hello world');
56// Prints: hello world, to out
57myConsole.log('hello %s', 'world');
58// Prints: hello world, to out
59myConsole.error(new Error('Whoops, something bad happened'));
60// Prints: [Error: Whoops, something bad happened], to err
61
62const name = 'Will Robinson';
63myConsole.warn(`Danger ${name}! Danger!`);
64// Prints: Danger Will Robinson! Danger!, to err
65```
66
67## Class: `Console`
68
69<!-- YAML
70changes:
71  - version: v8.0.0
72    pr-url: https://github.com/nodejs/node/pull/9744
73    description: Errors that occur while writing to the underlying streams
74                 will now be ignored by default.
75-->
76
77<!--type=class-->
78
79The `Console` class can be used to create a simple logger with configurable
80output streams and can be accessed using either `require('node:console').Console`
81or `console.Console` (or their destructured counterparts):
82
83```js
84const { Console } = require('node:console');
85```
86
87```js
88const { Console } = console;
89```
90
91### `new Console(stdout[, stderr][, ignoreErrors])`
92
93### `new Console(options)`
94
95<!-- YAML
96changes:
97  - version:
98     - v14.2.0
99     - v12.17.0
100    pr-url: https://github.com/nodejs/node/pull/32964
101    description: The `groupIndentation` option was introduced.
102  - version: v11.7.0
103    pr-url: https://github.com/nodejs/node/pull/24978
104    description: The `inspectOptions` option is introduced.
105  - version: v10.0.0
106    pr-url: https://github.com/nodejs/node/pull/19372
107    description: The `Console` constructor now supports an `options` argument,
108                 and the `colorMode` option was introduced.
109  - version: v8.0.0
110    pr-url: https://github.com/nodejs/node/pull/9744
111    description: The `ignoreErrors` option was introduced.
112-->
113
114* `options` {Object}
115  * `stdout` {stream.Writable}
116  * `stderr` {stream.Writable}
117  * `ignoreErrors` {boolean} Ignore errors when writing to the underlying
118    streams. **Default:** `true`.
119  * `colorMode` {boolean|string} Set color support for this `Console` instance.
120    Setting to `true` enables coloring while inspecting values. Setting to
121    `false` disables coloring while inspecting values. Setting to
122    `'auto'` makes color support depend on the value of the `isTTY` property
123    and the value returned by `getColorDepth()` on the respective stream. This
124    option can not be used, if `inspectOptions.colors` is set as well.
125    **Default:** `'auto'`.
126  * `inspectOptions` {Object} Specifies options that are passed along to
127    [`util.inspect()`][].
128  * `groupIndentation` {number} Set group indentation.
129    **Default:** `2`.
130
131Creates a new `Console` with one or two writable stream instances. `stdout` is a
132writable stream to print log or info output. `stderr` is used for warning or
133error output. If `stderr` is not provided, `stdout` is used for `stderr`.
134
135```js
136const output = fs.createWriteStream('./stdout.log');
137const errorOutput = fs.createWriteStream('./stderr.log');
138// Custom simple logger
139const logger = new Console({ stdout: output, stderr: errorOutput });
140// use it like console
141const count = 5;
142logger.log('count: %d', count);
143// In stdout.log: count 5
144```
145
146The global `console` is a special `Console` whose output is sent to
147[`process.stdout`][] and [`process.stderr`][]. It is equivalent to calling:
148
149```js
150new Console({ stdout: process.stdout, stderr: process.stderr });
151```
152
153### `console.assert(value[, ...message])`
154
155<!-- YAML
156added: v0.1.101
157changes:
158  - version: v10.0.0
159    pr-url: https://github.com/nodejs/node/pull/17706
160    description: The implementation is now spec compliant and does not throw
161                 anymore.
162-->
163
164* `value` {any} The value tested for being truthy.
165* `...message` {any} All arguments besides `value` are used as error message.
166
167`console.assert()` writes a message if `value` is [falsy][] or omitted. It only
168writes a message and does not otherwise affect execution. The output always
169starts with `"Assertion failed"`. If provided, `message` is formatted using
170[`util.format()`][].
171
172If `value` is [truthy][], nothing happens.
173
174```js
175console.assert(true, 'does nothing');
176
177console.assert(false, 'Whoops %s work', 'didn\'t');
178// Assertion failed: Whoops didn't work
179
180console.assert();
181// Assertion failed
182```
183
184### `console.clear()`
185
186<!-- YAML
187added: v8.3.0
188-->
189
190When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
191TTY. When `stdout` is not a TTY, this method does nothing.
192
193The specific operation of `console.clear()` can vary across operating systems
194and terminal types. For most Linux operating systems, `console.clear()`
195operates similarly to the `clear` shell command. On Windows, `console.clear()`
196will clear only the output in the current terminal viewport for the Node.js
197binary.
198
199### `console.count([label])`
200
201<!-- YAML
202added: v8.3.0
203-->
204
205* `label` {string} The display label for the counter. **Default:** `'default'`.
206
207Maintains an internal counter specific to `label` and outputs to `stdout` the
208number of times `console.count()` has been called with the given `label`.
209
210<!-- eslint-skip -->
211
212```js
213> console.count()
214default: 1
215undefined
216> console.count('default')
217default: 2
218undefined
219> console.count('abc')
220abc: 1
221undefined
222> console.count('xyz')
223xyz: 1
224undefined
225> console.count('abc')
226abc: 2
227undefined
228> console.count()
229default: 3
230undefined
231>
232```
233
234### `console.countReset([label])`
235
236<!-- YAML
237added: v8.3.0
238-->
239
240* `label` {string} The display label for the counter. **Default:** `'default'`.
241
242Resets the internal counter specific to `label`.
243
244<!-- eslint-skip -->
245
246```js
247> console.count('abc');
248abc: 1
249undefined
250> console.countReset('abc');
251undefined
252> console.count('abc');
253abc: 1
254undefined
255>
256```
257
258### `console.debug(data[, ...args])`
259
260<!-- YAML
261added: v8.0.0
262changes:
263  - version: v8.10.0
264    pr-url: https://github.com/nodejs/node/pull/17033
265    description: "`console.debug` is now an alias for `console.log`."
266-->
267
268* `data` {any}
269* `...args` {any}
270
271The `console.debug()` function is an alias for [`console.log()`][].
272
273### `console.dir(obj[, options])`
274
275<!-- YAML
276added: v0.1.101
277-->
278
279* `obj` {any}
280* `options` {Object}
281  * `showHidden` {boolean} If `true` then the object's non-enumerable and symbol
282    properties will be shown too. **Default:** `false`.
283  * `depth` {number} Tells [`util.inspect()`][] how many times to recurse while
284    formatting the object. This is useful for inspecting large complicated
285    objects. To make it recurse indefinitely, pass `null`. **Default:** `2`.
286  * `colors` {boolean} If `true`, then the output will be styled with ANSI color
287    codes. Colors are customizable;
288    see [customizing `util.inspect()` colors][]. **Default:** `false`.
289
290Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`.
291This function bypasses any custom `inspect()` function defined on `obj`.
292
293### `console.dirxml(...data)`
294
295<!-- YAML
296added: v8.0.0
297changes:
298  - version: v9.3.0
299    pr-url: https://github.com/nodejs/node/pull/17152
300    description: "`console.dirxml` now calls `console.log` for its arguments."
301-->
302
303* `...data` {any}
304
305This method calls `console.log()` passing it the arguments received.
306This method does not produce any XML formatting.
307
308### `console.error([data][, ...args])`
309
310<!-- YAML
311added: v0.1.100
312-->
313
314* `data` {any}
315* `...args` {any}
316
317Prints to `stderr` with newline. Multiple arguments can be passed, with the
318first used as the primary message and all additional used as substitution
319values similar to printf(3) (the arguments are all passed to
320[`util.format()`][]).
321
322```js
323const code = 5;
324console.error('error #%d', code);
325// Prints: error #5, to stderr
326console.error('error', code);
327// Prints: error 5, to stderr
328```
329
330If formatting elements (e.g. `%d`) are not found in the first string then
331[`util.inspect()`][] is called on each argument and the resulting string
332values are concatenated. See [`util.format()`][] for more information.
333
334### `console.group([...label])`
335
336<!-- YAML
337added: v8.5.0
338-->
339
340* `...label` {any}
341
342Increases indentation of subsequent lines by spaces for `groupIndentation`
343length.
344
345If one or more `label`s are provided, those are printed first without the
346additional indentation.
347
348### `console.groupCollapsed()`
349
350<!-- YAML
351  added: v8.5.0
352-->
353
354An alias for [`console.group()`][].
355
356### `console.groupEnd()`
357
358<!-- YAML
359added: v8.5.0
360-->
361
362Decreases indentation of subsequent lines by spaces for `groupIndentation`
363length.
364
365### `console.info([data][, ...args])`
366
367<!-- YAML
368added: v0.1.100
369-->
370
371* `data` {any}
372* `...args` {any}
373
374The `console.info()` function is an alias for [`console.log()`][].
375
376### `console.log([data][, ...args])`
377
378<!-- YAML
379added: v0.1.100
380-->
381
382* `data` {any}
383* `...args` {any}
384
385Prints to `stdout` with newline. Multiple arguments can be passed, with the
386first used as the primary message and all additional used as substitution
387values similar to printf(3) (the arguments are all passed to
388[`util.format()`][]).
389
390```js
391const count = 5;
392console.log('count: %d', count);
393// Prints: count: 5, to stdout
394console.log('count:', count);
395// Prints: count: 5, to stdout
396```
397
398See [`util.format()`][] for more information.
399
400### `console.table(tabularData[, properties])`
401
402<!-- YAML
403added: v10.0.0
404-->
405
406* `tabularData` {any}
407* `properties` {string\[]} Alternate properties for constructing the table.
408
409Try to construct a table with the columns of the properties of `tabularData`
410(or use `properties`) and rows of `tabularData` and log it. Falls back to just
411logging the argument if it can't be parsed as tabular.
412
413```js
414// These can't be parsed as tabular data
415console.table(Symbol());
416// Symbol()
417
418console.table(undefined);
419// undefined
420
421console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
422// ┌─────────┬─────┬─────┐
423// │ (index) │  a  │  b  │
424// ├─────────┼─────┼─────┤
425// │    0    │  1  │ 'Y' │
426// │    1    │ 'Z' │  2  │
427// └─────────┴─────┴─────┘
428
429console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
430// ┌─────────┬─────┐
431// │ (index) │  a  │
432// ├─────────┼─────┤
433// │    0    │  1  │
434// │    1    │ 'Z' │
435// └─────────┴─────┘
436```
437
438### `console.time([label])`
439
440<!-- YAML
441added: v0.1.104
442-->
443
444* `label` {string} **Default:** `'default'`
445
446Starts a timer that can be used to compute the duration of an operation. Timers
447are identified by a unique `label`. Use the same `label` when calling
448[`console.timeEnd()`][] to stop the timer and output the elapsed time in
449suitable time units to `stdout`. For example, if the elapsed
450time is 3869ms, `console.timeEnd()` displays "3.869s".
451
452### `console.timeEnd([label])`
453
454<!-- YAML
455added: v0.1.104
456changes:
457  - version: v13.0.0
458    pr-url: https://github.com/nodejs/node/pull/29251
459    description: The elapsed time is displayed with a suitable time unit.
460  - version: v6.0.0
461    pr-url: https://github.com/nodejs/node/pull/5901
462    description: This method no longer supports multiple calls that don't map
463                 to individual `console.time()` calls; see below for details.
464-->
465
466* `label` {string} **Default:** `'default'`
467
468Stops a timer that was previously started by calling [`console.time()`][] and
469prints the result to `stdout`:
470
471```js
472console.time('bunch-of-stuff');
473// Do a bunch of stuff.
474console.timeEnd('bunch-of-stuff');
475// Prints: bunch-of-stuff: 225.438ms
476```
477
478### `console.timeLog([label][, ...data])`
479
480<!-- YAML
481added: v10.7.0
482-->
483
484* `label` {string} **Default:** `'default'`
485* `...data` {any}
486
487For a timer that was previously started by calling [`console.time()`][], prints
488the elapsed time and other `data` arguments to `stdout`:
489
490```js
491console.time('process');
492const value = expensiveProcess1(); // Returns 42
493console.timeLog('process', value);
494// Prints "process: 365.227ms 42".
495doExpensiveProcess2(value);
496console.timeEnd('process');
497```
498
499### `console.trace([message][, ...args])`
500
501<!-- YAML
502added: v0.1.104
503-->
504
505* `message` {any}
506* `...args` {any}
507
508Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`][]
509formatted message and stack trace to the current position in the code.
510
511```js
512console.trace('Show me');
513// Prints: (stack trace will vary based on where trace is called)
514//  Trace: Show me
515//    at repl:2:9
516//    at REPLServer.defaultEval (repl.js:248:27)
517//    at bound (domain.js:287:14)
518//    at REPLServer.runBound [as eval] (domain.js:300:12)
519//    at REPLServer.<anonymous> (repl.js:412:12)
520//    at emitOne (events.js:82:20)
521//    at REPLServer.emit (events.js:169:7)
522//    at REPLServer.Interface._onLine (readline.js:210:10)
523//    at REPLServer.Interface._line (readline.js:549:8)
524//    at REPLServer.Interface._ttyWrite (readline.js:826:14)
525```
526
527### `console.warn([data][, ...args])`
528
529<!-- YAML
530added: v0.1.100
531-->
532
533* `data` {any}
534* `...args` {any}
535
536The `console.warn()` function is an alias for [`console.error()`][].
537
538## Inspector only methods
539
540The following methods are exposed by the V8 engine in the general API but do
541not display anything unless used in conjunction with the [inspector][]
542(`--inspect` flag).
543
544### `console.profile([label])`
545
546<!-- YAML
547added: v8.0.0
548-->
549
550* `label` {string}
551
552This method does not display anything unless used in the inspector. The
553`console.profile()` method starts a JavaScript CPU profile with an optional
554label until [`console.profileEnd()`][] is called. The profile is then added to
555the **Profile** panel of the inspector.
556
557```js
558console.profile('MyLabel');
559// Some code
560console.profileEnd('MyLabel');
561// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
562```
563
564### `console.profileEnd([label])`
565
566<!-- YAML
567added: v8.0.0
568-->
569
570* `label` {string}
571
572This method does not display anything unless used in the inspector. Stops the
573current JavaScript CPU profiling session if one has been started and prints
574the report to the **Profiles** panel of the inspector. See
575[`console.profile()`][] for an example.
576
577If this method is called without a label, the most recently started profile is
578stopped.
579
580### `console.timeStamp([label])`
581
582<!-- YAML
583added: v8.0.0
584-->
585
586* `label` {string}
587
588This method does not display anything unless used in the inspector. The
589`console.timeStamp()` method adds an event with the label `'label'` to the
590**Timeline** panel of the inspector.
591
592[`console.error()`]: #consoleerrordata-args
593[`console.group()`]: #consolegrouplabel
594[`console.log()`]: #consolelogdata-args
595[`console.profile()`]: #consoleprofilelabel
596[`console.profileEnd()`]: #consoleprofileendlabel
597[`console.time()`]: #consoletimelabel
598[`console.timeEnd()`]: #consoletimeendlabel
599[`process.stderr`]: process.md#processstderr
600[`process.stdout`]: process.md#processstdout
601[`util.format()`]: util.md#utilformatformat-args
602[`util.inspect()`]: util.md#utilinspectobject-options
603[customizing `util.inspect()` colors]: util.md#customizing-utilinspect-colors
604[falsy]: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
605[inspector]: debugger.md
606[note on process I/O]: process.md#a-note-on-process-io
607[truthy]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
608