• Node.js Video Tutorials

NodeJS - console.warn() Method



The Node.js console.warn() method will print the warning messages as an output on the console. It prints the output to stderr with a new line. The message argument provided to this method must be either a string or an object that can be converted into a string using the util.inspect() function in order for it to work properly. It is almost similar to the console.error() method of node.js. This method is useful on daily life web pages to show the error messages on the console.

Syntax

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

console.warn( [data][, ...args] )

Parameters

This method accepts multiple parameters and those are discussed below.

  • In the data parameter, we pass the message that should display on the console.

  • The second parameter args is the substitution value for the message we passed inside the data parameter.

Return value

This function will return a warning message on the console with the parameters we passed inside it.

Example

In the example below, we are passing a message into the data parameter of the method.

console.warn("This is an error statement");

Output

As we can see in the output, the Node.js console.warn() method printed an error with the message passed on the console.

This is an error statement

Example

In the following example below, we are running a loop and inside the loop, we are calling the console.warn() method with a data parameter.

for(i = 1; i <= 10; i++)
{
   console.warn("This is error statement: " + i);
}	

Output

As we can see in the output, for every iteration we are getting warnings with the message we passed inside the function.

This is error statement: 1
This is error statement: 2
This is error statement: 3
This is error statement: 4
This is error statement: 5
This is error statement: 6
This is error statement: 7
This is error statement: 8
This is error statement: 9
This is error statement: 10

Example

In the example below,

  • We are declaring two integer variables and performing multiplication and subtraction operations on them.

  • Then, we are using the 'if' statement, and if the condition is satisfied then console.warn() method will get executed.

var a = 10;
var b = 15;
var c = a * b;
var d = b - a;
if (c > d){
   console.warn( c + " is %s than " + d, 'greater');
}

Output

As we can see in the output below, the condition is satisfied and the console.warn() method is executed.

150 is greater than 5
nodejs_console_module.htm
Advertisements