- Output to the command line using Node.js
- console
- Instance methods
- Examples
- Outputting text to the console
- Outputting a single object
- Outputting multiple objects
- Using string substitutions
- Styling console output
- Using groups in the console
- Timers
- Stack traces
- Specifications
- Browser compatibility
- Notes
- See also
- Other implementations
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
Output to the command line using Node.js
Node.js provides a console module which provides tons of very useful ways to interact with the command line.
It is basically the same as the console object you find in the browser.
The most basic and most used method is console.log() , which prints the string you pass to it to the console.
If you pass an object, it will render it as a string.
You can pass multiple variables to console.log , for example:
and Node.js will print both.
We can also format pretty phrases by passing variables and a format specifier.
- %s format a variable as a string
- %d format a variable as a number
- %i format a variable as its integer part only
- %o format a variable as an object
console.clear() clears the console (the behavior might depend on the console used)
console.count() is a handy method.
What happens is that console.count() will count the number of times a string is printed, and print the count next to it:
You can just count apples and oranges:
The console.countReset() method resets counter used with console.count().
We will use the apples and orange example to demonstrate this.
Notice how the call to console.countReset(‘orange’) resets the value counter to zero.
There might be cases where it’s useful to print the call stack trace of a function, maybe to answer the question how did you reach that part of the code?
You can do so using console.trace() :
This will print the stack trace. This is what’s printed if we try this in the Node.js REPL:
You can easily calculate how much time a function takes to run, using time() and timeEnd()
As we saw console.log is great for printing messages in the Console. This is what’s called the standard output, or stdout .
console.error prints to the stderr stream.
It will not appear in the console, but it will appear in the error log.
You can color the output of your text in the console by using escape sequences. An escape sequence is a set of characters that identifies a color.
You can try that in the Node.js REPL, and it will print hi! in yellow.
However, this is the low-level way to do this. The simplest way to go about coloring the console output is by using a library. Chalk is such a library, and in addition to coloring it also helps with other styling facilities, like making text bold, italic or underlined.
You install it with npm install chalk@4 , then you can use it:
Using chalk.yellow is much more convenient than trying to remember the escape codes, and the code is much more readable.
Check the project link posted above for more usage examples.
Progress is an awesome package to create a progress bar in the console. Install it using npm install progress
This snippet creates a 10-step progress bar, and every 100ms one step is completed. When the bar completes we clear the interval:
console
The console object provides access to the browser’s debugging console (e.g. the Web console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided.
The console object can be accessed from any global object. Window on browsing scopes and WorkerGlobalScope as specific variants in workers via the property console. It’s exposed as Window.console , and can be referenced as console . For example:
.log("Failed to open the specified link");
This page documents the Methods available on the console object and gives a few Usage examples.
Note: This feature is available in Web Workers
Note: Certain online IDEs and editors may implement the console API differently than the browsers. As a result, certain functionality of the console API, such as the timer methods, may not be outputted in the console of online IDEs or editors. Always open your browser’s DevTools console to see the logs as shown in this documentation.
Instance methods
Log a message and stack trace to console if the first argument is false .
Log the number of times this line has been called with the given label.
Resets the value of the counter with the given label.
Outputs a message to the console with the log level debug .
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.
Outputs an error message. You may use string substitution and additional arguments with this method.
console.exception() Non-standard Deprecated
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd() .
Creates a new inline group, indenting all following output by another level. However, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd() .
Informative logging of information. You may use string substitution and additional arguments with this method.
For general output of logging information. You may use string substitution and additional arguments with this method.
Starts the browser’s built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
Stops the profiler. You can see the resulting profile in the browser’s performance tool (for example, the Firefox performance tool).
Displays tabular data as a table.
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
Stops the specified timer and logs the elapsed time in milliseconds since it started.
Logs the value of the specified timer to the console.
Adds a marker to the browser performance tool’s timeline (Chrome or Firefox).
Outputs a warning message. You may use string substitution and additional arguments with this method.
Examples
Outputting text to the console
The most frequently-used feature of the console is logging of text and other data. There are several categories of output you can generate, using the console.log() , console.info() , console.warn() , console.error() , or console.debug() methods. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.
There are two ways to use each of the output methods; you can pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.
Outputting a single object
The simplest way to use the logging methods is to output a single object:
const someObject = str: "Some text", id: 5 >; console.log(someObject);
The output looks something like this:
Outputting multiple objects
You can also output multiple objects by listing them when calling the logging method, like this:
const car = "Dodge Charger"; const someObject = str: "Some text", id: 5 >; console.info("My first car was a", car, ". The object is:", someObject);
The output will look like this:
Using string substitutions
When passing a string to one of the console object’s methods that accepts a string (such as log() ), you may use these substitution strings:
Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
Outputs an integer. Number formatting is supported, for example console.log(«Foo %.2d», 1.1) will output the number as two significant figures with a leading 0: Foo 01 .
Outputs a floating-point value. Formatting is supported, for example console.log(«Foo %.2f», 1.1) will output the number to 2 decimal places: Foo 1.10 .
Note: Precision formatting doesn’t work in Chrome.
Each of these pulls the next argument after the format string off the parameter list. For example:
for (let i = 0; i 5; i++) console.log("Hello, %s. You've called me %d times.", "Bob", i + 1); >
The output looks like this:
Hello, Bob. You've called me 1 times. Hello, Bob. You've called me 2 times. Hello, Bob. You've called me 3 times. Hello, Bob. You've called me 4 times. Hello, Bob. You've called me 5 times.
Styling console output
You can use the %c directive to apply a CSS style to console output:
.log( "This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px", );
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
You may use %c multiple times:
.log( "Multiple styles: %cred %corange", "color: red", "color: orange", "Additional unformatted message", );
The properties usable along with the %c syntax are as follows (at least, in Firefox — they may differ in other browsers):
- background and its longhand equivalents
- border and its longhand equivalents
- border-radius
- box-decoration-break
- box-shadow
- clear and float
- color
- cursor
- display
- font and its longhand equivalents
- line-height
- margin
- outline and its longhand equivalents
- padding
- text-* properties such as text-transform
- white-space
- word-spacing and word-break
- writing-mode
Note: The console message behaves like an inline element by default. To see the effects of padding , margin , etc. you should set it to for example display: inline-block .
Using groups in the console
You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group() . The console.groupCollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.
To exit the current group, call console.groupEnd() . For example, given this code:
.log("This is the outer level"); console.group("First group"); console.log("In the first group"); console.group("Second group"); console.log("In the second group"); console.warn("Still in the second group"); console.groupEnd(); console.log("Back to the first group"); console.groupEnd(); console.debug("Back to the outer level");
The output looks like this:
Timers
You can start a timer to calculate the duration of a specific operation. To start one, call the console.time() method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd() method, again passing the timer’s name as the parameter. Up to 10,000 timers can run simultaneously on a given page.
For example, given this code:
.time("answer time"); alert("Click to continue"); console.timeLog("answer time"); alert("Do a bunch of other stuff…"); console.timeEnd("answer time");
Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console:
Notice that the timer’s name is displayed both when the timer is started and when it’s stopped.
Note: It’s important to note that if you’re using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
Stack traces
The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call console.trace() . Given code like this:
function foo() function bar() console.trace(); > bar(); > foo();
The output in the console looks something like this:
Specifications
Browser compatibility
BCD tables only load in the browser
Notes
- At least in Firefox, if a page defines a console object, that object overrides the one built into Firefox.
See also
- Firefox Developer Tools
- Web console — how the Web console in Firefox handles console API calls
- about:debugging — how to see console output when the debugging target is a mobile device
Other implementations
Found a content problem with this page?
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.