• Node.js Video Tutorials

NodeJS - console.log() Method



The Node.js console.log() method is used to print the given messages to the standard output stream (stdout) ie. in the terminal or other logging mechanisms, such as a file or network connection. It takes any number of arguments and prints them out separated by spaces with a newline at the end.

Assume a scenario where we need to print some important messages on the console, to do that the console.log() method of node.js is useful. And also if we want to print any function's output etc. the console.log() method can do that task. To get a better understanding let's look into the syntax and usage of the console.log() method of node.js.

Syntax

Following is the syntax of the Node.js console.log() method −

console.log([data] [, …args]);

Parameters

This function accepts two parameters and those are demonstrated below.

  • data − This parameter specifies the message that will be shown on the console.

  • args − This is an optional parameter, it holds the substitution values that will be passed to the data.

Return value

This method doesn't return anything; instead, it prints the formatted message to stdout in a new line on the console.

Example

The Node.js console.log() method of node.js accepts a parameter (data).

In the example, we are calling the console.log() method with only a data parameter.

console.log("Welcome to Tutorialspoint");
console.log("Simply Easy Learning at your fingertips");

Output

As we can see in the output, the console.log() methods prints the message which we've passed as data.

Welcome to Tutorialspoint
Simply Easy Learning at your fingertips

Example

The console.info() method of node.js will accept an optional parameter (args).

In this example, we are calling the console.log() function with two parameters data and args. We are passing string values as substitution values.

console.log("%s to %s", "Welcome", "Tutorialspoint");
console.log("%s Easy Learning at your %s", "Simply", "fingertips");

Output

As we can see in the output, the message we passed into data is printed to stdout in a newline along with the substitution values which we passed as args.

Welcome to Tutorialspoint
Simply Easy Learning at your fingertips

Example

In the example below, We are doing similar to the above example, but instead of passing string values as args, we are passing integer values.

console.log("Bahubali - %d, Bahubali - %d", 1,2);
console.log("Bahubali - %d collected %d crores around the globe", 2, 2000);

Output

As we can see in the output, the substitution values are passed into the data and are printed to stdout in a newline.

Bahubali - 1, Bahubali - 2
Bahubali - 2 collected 2000 crores around the globe
nodejs_console_module.htm
Advertisements