Node.js – Process Warning Event

Node.jsServer Side ProgrammingProgramming

<p>A &#39;<strong>warning</strong>&#39; 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&#39;s attention.</p><p>Node.js can emit warnings whenever it encounters any bad coding practices that could lead to poor performance or bugs.</p><h2>Syntax</h2><pre class="prettyprint notranslate">Event : &#39;warning&#39;</pre><h2>Example 1</h2><p>Create a file with the name &quot;<strong>warning.js</strong>&quot; and copy the following code. After creating the file, use the command &quot;<strong>node warning.js</strong>&quot; to run this code, as shown in the example below</p><pre class="demo-code notranslate language-node" data-lang="node">// Event: warning Demo Example // Importing the process module const process = require(&#39;process&#39;); // Intentionally emited warning process.emitWarning(&#39;This might raise a Warning&#39;); // Firing a warning event process.on(&#39;warning&#39;, (warning) =&gt; { console.warn(&quot;Warning: &quot; + warning.name); console.warn(&quot;Warning Message - &quot; + warning.message); });</pre><h2>Output</h2><pre class="result notranslate">(node:34720) Warning: This might raise a Warning Warning: Warning Warning Message - This might raise a Warning</pre><h2>Example 2</h2><p>Let&#39;s take a look at one more example.</p><pre class="demo-code notranslate language-node" data-lang="node">// Event: Warning Demo Example // Importing the process module const process = require(&#39;process&#39;); // Intentionally emited warning process.emitWarning(&#39;CPU Usage is more than 90%&#39;); // Firing a warning event process.on(&#39;warning&#39;, (warning) =&gt; { console.warn(&quot;warning stacktrace - &quot; + warning.stack) });</pre><h2>Output</h2><pre class="result notranslate">(node:38330) Warning: CPU Usage is more than 90% warning stacktrace - Warning: CPU Usage is more than 90% &nbsp; &nbsp;at Object.&lt;anonymous&gt; (/home/cg/root/4591873/main.js:5:9) &nbsp; &nbsp;at Module._compile (module.js:570:32) &nbsp; &nbsp;at Object.Module._extensions..js (module.js:579:10) &nbsp; &nbsp;at Module.load (module.js:487:32) &nbsp; &nbsp;at tryModuleLoad (module.js:446:12) &nbsp; &nbsp;at Function.Module._load (module.js:438:3) &nbsp; &nbsp;at Module.runMain (module.js:604:10) &nbsp; &nbsp;at run (bootstrap_node.js:389:7) &nbsp; &nbsp;at startup (bootstrap_node.js:149:9) &nbsp; &nbsp;at bootstrap_node.js:504:3</pre>
raja
Updated on 24-Nov-2021 07:15:45

Advertisements