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