Node.js – Process Warning Event


A 'warning' event is emitted whenever a Node.js event emits a process warning. The process warning is similar to an error that describes the exceptional conditions that are being brought to the user's attention.

Node.js can emit warnings whenever it encounters any bad coding practices that could lead to poor performance or bugs.

Syntax

Event : 'warning'

Example 1

Create a file with the name "warning.js" and copy the following code. After creating the file, use the command "node warning.js" to run this code, as shown in the example below

// Event: warning Demo Example

// Importing the process module
const process = require('process');

// Intentionally emited warning
process.emitWarning('This might raise a Warning');

// Firing a warning event
process.on('warning', (warning) => {
   console.warn("Warning: " + warning.name);
   console.warn("Warning Message - " + warning.message);
});

Output

(node:34720) Warning: This might raise a Warning
Warning: Warning
Warning Message - This might raise a Warning

Example 2

Let's take a look at one more example.

// Event: Warning Demo Example

// Importing the process module
const process = require('process');

// Intentionally emited warning
process.emitWarning('CPU Usage is more than 90%');

// Firing a warning event
process.on('warning', (warning) => {
   console.warn("warning stacktrace - " + warning.stack)
});

Output

(node:38330) Warning: CPU Usage is more than 90%
warning stacktrace - Warning: CPU Usage is more than 90%
   at Object.<anonymous> (/home/cg/root/4591873/main.js:5:9)
   at Module._compile (module.js:570:32)
   at Object.Module._extensions..js (module.js:579:10)
   at Module.load (module.js:487:32)
   at tryModuleLoad (module.js:446:12)
   at Function.Module._load (module.js:438:3)
   at Module.runMain (module.js:604:10)
   at run (bootstrap_node.js:389:7)
   at startup (bootstrap_node.js:149:9)
   at bootstrap_node.js:504:3

Updated on: 24-Nov-2021

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements