title: Node.js, Express, EJS - refresh variable to output on page
body: <p>So I have set up a Node.js server and displaying a page that shows the current CPU usage, the problem now is that I have to refresh the entire page for the variable to update, and if I just update the variable via JavaScript, it shows the right CPU usage directly after refreshing the page, but after the interval runs out, it just outputs "undefined".</p>
  
  <p>Node.js Code:</p>
  
  <pre><code>var cpuusage = 0;
  var percent = require('cpu-percent');
  percent(function(err,percent){
      if(err) { }else{
          cpuusage = Math.round(percent);
      }
  });
  </code></pre>
  
  <p>^ Getting the current CPU usage</p>
  
  <pre><code>app.get("/", function (req, res) {
      res.render("default.ejs", {
          "cpu":cpuusage
      });
  });
  </code></pre>
  
  <p>^ Assigning the value to the EJS template</p>
  
  <p>default.ejs code:</p>
  
  <pre><code>&lt;b&gt;CPU&lt;/b&gt;: &lt;span id="showCpu"&gt;&lt;%= cpu  %&gt;&lt;/span&gt;% &lt;br&gt;
  &lt;script&gt;
      function updateCPU(){
          document.getElementById("showCpu").innerHTML="&lt;%= cpu %&gt;";
      }
      setInterval("updateCPU()", 2000);
  &lt;/script&gt;
  </code></pre>
  
  <p>^ Outputting the variable value and then refreshing the span</p>