Source Code: lib/console.js
The node:console module provides a simple debugging console that is similar to\nthe JavaScript console mechanism provided by web browsers.
node:console
The module exports two specific components:
Console
console.log()
console.error()
console.warn()
console
process.stdout
process.stderr
require('node:console')
Warning: The global console object's methods are neither consistently\nsynchronous like the browser APIs they resemble, nor are they consistently\nasynchronous like all other Node.js streams. See the note on process I/O for\nmore information.
Example using the global console:
console.log('hello world');\n// Prints: hello world, to stdout\nconsole.log('hello %s', 'world');\n// Prints: hello world, to stdout\nconsole.error(new Error('Whoops, something bad happened'));\n// Prints error message and stack trace to stderr:\n// Error: Whoops, something bad happened\n// at [eval]:5:15\n// at Script.runInThisContext (node:vm:132:18)\n// at Object.runInThisContext (node:vm:309:38)\n// at node:internal/process/execution:77:19\n// at [eval]-wrapper:6:22\n// at evalScript (node:internal/process/execution:76:60)\n// at node:internal/main/eval_string:23:3\n\nconst name = 'Will Robinson';\nconsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to stderr\n
Example using the Console class:
const out = getStreamSomehow();\nconst err = getStreamSomehow();\nconst myConsole = new console.Console(out, err);\n\nmyConsole.log('hello world');\n// Prints: hello world, to out\nmyConsole.log('hello %s', 'world');\n// Prints: hello world, to out\nmyConsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: Whoops, something bad happened], to err\n\nconst name = 'Will Robinson';\nmyConsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to err\n
The Console class can be used to create a simple logger with configurable\noutput streams and can be accessed using either require('node:console').Console\nor console.Console (or their destructured counterparts):
require('node:console').Console
console.Console
const { Console } = require('node:console');\n
const { Console } = console;\n
console.assert() writes a message if value is falsy or omitted. It only\nwrites a message and does not otherwise affect execution. The output always\nstarts with \"Assertion failed\". If provided, message is formatted using\nutil.format().
console.assert()
value
\"Assertion failed\"
message
util.format()
If value is truthy, nothing happens.
console.assert(true, 'does nothing');\n\nconsole.assert(false, 'Whoops %s work', 'didn\\'t');\n// Assertion failed: Whoops didn't work\n\nconsole.assert();\n// Assertion failed\n
When stdout is a TTY, calling console.clear() will attempt to clear the\nTTY. When stdout is not a TTY, this method does nothing.
stdout
console.clear()
The specific operation of console.clear() can vary across operating systems\nand terminal types. For most Linux operating systems, console.clear()\noperates similarly to the clear shell command. On Windows, console.clear()\nwill clear only the output in the current terminal viewport for the Node.js\nbinary.
clear
Maintains an internal counter specific to label and outputs to stdout the\nnumber of times console.count() has been called with the given label.
label
console.count()
> console.count()\ndefault: 1\nundefined\n> console.count('default')\ndefault: 2\nundefined\n> console.count('abc')\nabc: 1\nundefined\n> console.count('xyz')\nxyz: 1\nundefined\n> console.count('abc')\nabc: 2\nundefined\n> console.count()\ndefault: 3\nundefined\n>\n
Resets the internal counter specific to label.
> console.count('abc');\nabc: 1\nundefined\n> console.countReset('abc');\nundefined\n> console.count('abc');\nabc: 1\nundefined\n>\n
The console.debug() function is an alias for console.log().
console.debug()
Uses util.inspect() on obj and prints the resulting string to stdout.\nThis function bypasses any custom inspect() function defined on obj.
util.inspect()
obj
inspect()
This method calls console.log() passing it the arguments received.\nThis method does not produce any XML formatting.
Prints to stderr with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()).
stderr
printf(3)
const code = 5;\nconsole.error('error #%d', code);\n// Prints: error #5, to stderr\nconsole.error('error', code);\n// Prints: error 5, to stderr\n
If formatting elements (e.g. %d) are not found in the first string then\nutil.inspect() is called on each argument and the resulting string\nvalues are concatenated. See util.format() for more information.
%d
Increases indentation of subsequent lines by spaces for groupIndentation\nlength.
groupIndentation
If one or more labels are provided, those are printed first without the\nadditional indentation.
An alias for console.group().
console.group()
Decreases indentation of subsequent lines by spaces for groupIndentation\nlength.
The console.info() function is an alias for console.log().
console.info()
Prints to stdout with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()).
const count = 5;\nconsole.log('count: %d', count);\n// Prints: count: 5, to stdout\nconsole.log('count:', count);\n// Prints: count: 5, to stdout\n
See util.format() for more information.
Try to construct a table with the columns of the properties of tabularData\n(or use properties) and rows of tabularData and log it. Falls back to just\nlogging the argument if it can't be parsed as tabular.
tabularData
properties
// These can't be parsed as tabular data\nconsole.table(Symbol());\n// Symbol()\n\nconsole.table(undefined);\n// undefined\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);\n// ┌─────────┬─────┬─────┐\n// │ (index) │ a │ b │\n// ├─────────┼─────┼─────┤\n// │ 0 │ 1 │ 'Y' │\n// │ 1 │ 'Z' │ 2 │\n// └─────────┴─────┴─────┘\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);\n// ┌─────────┬─────┐\n// │ (index) │ a │\n// ├─────────┼─────┤\n// │ 0 │ 1 │\n// │ 1 │ 'Z' │\n// └─────────┴─────┘\n
Starts a timer that can be used to compute the duration of an operation. Timers\nare identified by a unique label. Use the same label when calling\nconsole.timeEnd() to stop the timer and output the elapsed time in\nsuitable time units to stdout. For example, if the elapsed\ntime is 3869ms, console.timeEnd() displays \"3.869s\".
console.timeEnd()
Stops a timer that was previously started by calling console.time() and\nprints the result to stdout:
console.time()
console.time('bunch-of-stuff');\n// Do a bunch of stuff.\nconsole.timeEnd('bunch-of-stuff');\n// Prints: bunch-of-stuff: 225.438ms\n
For a timer that was previously started by calling console.time(), prints\nthe elapsed time and other data arguments to stdout:
data
console.time('process');\nconst value = expensiveProcess1(); // Returns 42\nconsole.timeLog('process', value);\n// Prints \"process: 365.227ms 42\".\ndoExpensiveProcess2(value);\nconsole.timeEnd('process');\n
Prints to stderr the string 'Trace: ', followed by the util.format()\nformatted message and stack trace to the current position in the code.
'Trace: '
console.trace('Show me');\n// Prints: (stack trace will vary based on where trace is called)\n// Trace: Show me\n// at repl:2:9\n// at REPLServer.defaultEval (repl.js:248:27)\n// at bound (domain.js:287:14)\n// at REPLServer.runBound [as eval] (domain.js:300:12)\n// at REPLServer.<anonymous> (repl.js:412:12)\n// at emitOne (events.js:82:20)\n// at REPLServer.emit (events.js:169:7)\n// at REPLServer.Interface._onLine (readline.js:210:10)\n// at REPLServer.Interface._line (readline.js:549:8)\n// at REPLServer.Interface._ttyWrite (readline.js:826:14)\n
The console.warn() function is an alias for console.error().
Creates a new Console with one or two writable stream instances. stdout is a\nwritable stream to print log or info output. stderr is used for warning or\nerror output. If stderr is not provided, stdout is used for stderr.
const output = fs.createWriteStream('./stdout.log');\nconst errorOutput = fs.createWriteStream('./stderr.log');\n// Custom simple logger\nconst logger = new Console({ stdout: output, stderr: errorOutput });\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// In stdout.log: count 5\n
The global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:
new Console({ stdout: process.stdout, stderr: process.stderr });\n
The following methods are exposed by the V8 engine in the general API but do\nnot display anything unless used in conjunction with the inspector\n(--inspect flag).
--inspect
This method does not display anything unless used in the inspector. The\nconsole.profile() method starts a JavaScript CPU profile with an optional\nlabel until console.profileEnd() is called. The profile is then added to\nthe Profile panel of the inspector.
console.profile()
console.profileEnd()
console.profile('MyLabel');\n// Some code\nconsole.profileEnd('MyLabel');\n// Adds the profile 'MyLabel' to the Profiles panel of the inspector.\n
This method does not display anything unless used in the inspector. Stops the\ncurrent JavaScript CPU profiling session if one has been started and prints\nthe report to the Profiles panel of the inspector. See\nconsole.profile() for an example.
If this method is called without a label, the most recently started profile is\nstopped.
This method does not display anything unless used in the inspector. The\nconsole.timeStamp() method adds an event with the label 'label' to the\nTimeline panel of the inspector.
console.timeStamp()
'label'