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