I'm trying to get CPU usage displayed onto a web app. I was following this video: https://www.youtube.com/watch?v=N8kqK9srXu8 . The video uses express, but I opted against this as I'm still new to node. I got to the point where he uses socket.io to pipe information to the front end. I get Uncaught ReferenceError: io is not defined.
and the line reference is when I call var socket = io('http://localhost');
or var socket = io();
. Here's the node code:
const http = require('http');
const path = require('path');
const fs = require('fs');
var io = require("socket.io")(http);
const os = require('os-utils');
indexPath = "C:\\Users\\Sebastian\\Documents\\VScode\\Personal Projects\\Startpage\\startpage.html";
const server = http.createServer((req,res) => {
let filePath = path.join(
__dirname,
req.url === '/'? 'startpage.html': req.url
);
let extname = path.extname(filePath);
let contentType = 'text/html';
switch(extname){
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
}
fs.readFile(filePath,
(err,content) =>{
res.writeHead(200, {'Content-Type': contentType});
res.end(content, 'utf8');
});
});
var histogramLength = 61;
var cpuHist = [];
var interval = 100;
const PORT = process.env.PORT || 5000;
server.listen(PORT, () =>{
console.log(`Server running on port ${PORT}`);
for( var i = 0; i < histogramLength; i++) cpuHist[i] = [i,0];
//sets interval to check cpu usage
setInterval(
() => {
//console.log(os.cpuUsage(() => console.log(" ")));
os.cpuUsage((value) => io.emit("cpu histogram", value));
},
interval);
});
Here's the relevant portion of my html:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Home</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style/startpage.css" class="style">
<link href="https://fonts.googleapis.com/css?family=Share+Tech+Mono&display=swap" rel="stylesheet">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src ="/socket.io/socket.io.js"> </script>
<script>
google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.setOnLoadCallback(drawBasic);
var chartLoaded = false;
var histogram = [];
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Dogs');
//data.addRows();
var options = {
colors: ['white'],
hAxis: {
title: 'Time',
textStyle: {
color: "white",
fontName: 'Share Tech Mono',
fontSize: 12,
bold: false,
italic: false
}
},
vAxis: {
title: 'CPU Usage',
textStyle: {
color: "white",
fontName: 'Share Tech Mono',
fontSize: 12,
bold: false,
italic: false
},
viewWindow:{
min: 0,
max: 100
}
},
chartArea: {
left: 5,
top: 5,
right: 5,
bottom: 5,
},
backgroundColor: "black",
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
chartLoaded = true;
}
var socket = io('http://localhost');
socket.on("cpu histogram", (cpuHistogram) => console.log(cpuHistogram));
</script> </script>
</head>
I read the socket.io documentation, and I feel like I'm adhering to it. I saw there was a similar post already: socket.io - ReferenceError: io is not defined . I tried the most upvoted fixes such as sourcing like this http://yourwebsite.com:12345/socket.io/socket.io.js
and using bower, and had no luck. I wrote my callback functions slightly differently than the guy in the video, and I print undefined
rather than the value of my cpu usage when I attempt to console log os.cpuUsage()
. Is there anything wrong with this or how I used socket.io? How can I get this to work?