make a node.js that will show cpu and ram usage with graph and Its only two file…
- User
make a node.js that will show cpu and ram usage with graph and Its only two file server.js and index.html just node server.js
- Assistant
make a node.js that will show cpu and ram usage with graph and Its only two file server.js and index.html just node server.js
Sure! Below is a simple Node.js application that displays CPU and RAM usage with real-time graphs. The application consists of two files: server.js and index.html. We'll use Express for the server and Chart.js for rendering the graphs on the client side.
Node.js Installed: Ensure you have Node.js installed on your machine. You can download it from here.
Initialize the Project: Create a new directory for your project and initialize it with npm.
mkdir system-monitor
cd system-monitor
npm init -y
Install Dependencies: Install the necessary Node.js packages.
npm install express socket.io
server.jsThis file sets up an Express server and uses Socket.io to emit CPU and RAM usage data to the client in real-time.
// server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const os = require('os');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Serve the index.html file
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Function to calculate CPU usage
function getCPUUsage() {
return new Promise((resolve) => {
const startMeasure = cpuAverage();
setTimeout(() => {
const endMeasure = cpuAverage();
const idleDifference = endMeasure.idle - startMeasure.idle;
const totalDifference = endMeasure.total - startMeasure.total;
const percentageCPU = 100 - Math.round(100 * idleDifference / totalDifference);
resolve(percentageCPU);
}, 100);
});
}
// Helper function to get average CPU times
function cpuAverage() {
const cpus = os.cpus();
let totalIdle = 0, totalTick = 0;
for(let cpu of cpus) {
for(type in cpu.times) {
totalTick += cpu.times[type];
}
totalIdle += cpu.times.idle;
}
return { idle: totalIdle / cpus.length, total: totalTick / cpus.length };
}
// When a client connects
io.on('connection', (socket) => {
console.log('a user connected');
// Send data every second
const interval = setInterval(async () => {
const cpu = await getCPUUsage();
const ram = Math.round(100 - (os.freemem() / os.totalmem()) * 100);
socket.emit('stats', { cpu, ram });
}, 1000);
// When the client disconnects
socket.on('disconnect', () => {
console.log('user disconnected');
clearInterval(interval);
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
index.htmlThis file sets up the client-side interface, connects to the server via Socket.io, and uses Chart.js to display real-time graphs of CPU and RAM usage.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CPU and RAM Usage Monitor</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f4;
}
.chart-container {
width: 80%;
margin: 50px auto;
}
</style>
</head>
<body>
<h1>CPU and RAM Usage Monitor</h1>
<div class="chart-container">
<canvas id="cpuChart"></canvas>
</div>
<div class="chart-container">
<canvas id="ramChart"></canvas>
</div>
<!-- Load Socket.io -->
<script src="/socket.io/socket.io.js"></script>
<!-- Load Chart.js from CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const socket = io();
// Initialize CPU Chart
const ctxCpu = document.getElementById('cpuChart').getContext('2d');
const cpuChart = new Chart(ctxCpu, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'CPU Usage (%)',
data: [],
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 2,
fill: false,
}]
},
options: {
responsive: true,
scales: {
x: { display: true, title: { display: true, text: 'Time (s)' } },
y: { beginAtZero: true, max: 100, title: { display: true, text: 'Usage (%)' } }
}
}
});
// Initialize RAM Chart
const ctxRam = document.getElementById('ramChart').getContext('2d');
const ramChart = new Chart(ctxRam, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'RAM Usage (%)',
data: [],
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2,
fill: false,
}]
},
options: {
responsive: true,
scales: {
x: { display: true, title: { display: true, text: 'Time (s)' } },
y: { beginAtZero: true, max: 100, title: { display: true, text: 'Usage (%)' } }
}
}
});
let time = 0;
socket.on('stats', (data) => {
time += 1;
// Update CPU Chart
cpuChart.data.labels.push(time);
cpuChart.data.datasets[0].data.push(data.cpu);
if (cpuChart.data.labels.length > 20) { // Keep last 20 data points
cpuChart.data.labels.shift();
cpuChart.data.datasets[0].data.shift();
}
cpuChart.update();
// Update RAM Chart
ramChart.data.labels.push(time);
ramChart.data.datasets[0].data.push(data.ram);
if (ramChart.data.labels.length > 20) { // Keep last 20 data points
ramChart.data.labels.shift();
ramChart.data.datasets[0].data.shift();
}
ramChart.update();
});
</script>
</body>
</html>
Server (server.js):
index.html file.Client (index.html):
stats events from the server and updates the charts in real-time.Start the Server:
Ensure you're in the project directory (system-monitor) and run:
node server.js
You should see an output like:
Server is running on port 3000
Access the Application:
Open your web browser and navigate to http://localhost:3000. You should see two real-time updating graphs displaying CPU and RAM usage.
Cross-Platform Compatibility: The CPU usage calculation method used should work on most platforms, but CPU metrics can vary slightly between operating systems.
Security Considerations: This example is for educational purposes and lacks security features. For production use, consider implementing security best practices.
Customization: You can customize the update interval, chart styles, and data window size as per your requirements.
This simple Node.js application provides a real-time visualization of your system's CPU and RAM usage using only two files: server.js and index.html. By leveraging Express and Socket.io on the server side and Chart.js on the client side, you can create a lightweight and efficient system monitor.
Not yet included in a published release.