0

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?

2 Answers2

1

To start with, this is incorrect:

require("socket.io")(http);

You need to pass your server there, not the http module and you need to assign the result to an io variable. So, after you've defined and initialized your server variable, you would do:

const io = require("socket.io")(server);

Now, io is a reference to your socket.io server instance on the server-side and it can be used to emit to all connected clients with io.emit(...).


Your client side error is likely because this <script> tag:

<script src ="/socket.io/socket.io.js"> </script>

is not working because your socket.io server was not initialized properly. It might sound counter-intuitive, but the socket.io server is what provides the response handler for the /socket.io/socket.io.js URL. When that is missing, it will cause io not to be defined in the client which will lead to the client-side error you report.


You may also want to reconsider trying to send the cpu usage value to the client 10 times per second. That's pretty frequent and with any decent number of clients, your server would be spending all of its time just sending data updates.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
-1

Use this package on the nodejs to create websockets:

const WebSocket = require('ws');

HarshaHR
  • 73
  • 4