Deven Rathore
Posted on February 19, 2023
In this tutorial, we will learn how to Build a server monitoring app with Vue and node, where we will talk about how we can use Vue.js, Node.js, Express.js, and, Socket.io together to create a powerful web application.
Steps to build a server monitoring app with Vue and node
- Install required packages - Backend
- Create the server
- Emit the real-data
- Update the server to emit data periodically
- Install required packages - Frontend
- Create the Vue.js App
- Set up the client to communicate with the server
- Create the components
- Create the server
- Run the App
Step 1 - Set up the backend
We will start by setting up the backend server using Node.js and Express.js.
1.1. Install required packages
First, create a new directory for our project and navigate into it. Then, initialize a new Node.js project and install the required packages.
mkdir server-monitoring-app
cd server-monitoring-app
npm init -y
npm install express socket.io cors
- express : To set up the web server and define routes.
- socket.io : To enable real-time communication between the client and the server.
- cors : To enable Cross-Origin Resource Sharing (CORS) for the server.
1.2. Create the server
Create a new file called server.js
and add the following code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const os = require('os');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const port = process.env.PORT || 4000;
app.use(cors());
app.get('/', (req, res) => {
res.send('Server is up and running');
});
server.listen(port, () => {
console.log(Server running on port ${port});
});
This code sets up an Express.js app with a basic route and a Socket.io server that listens on the specified port. We have also added a CORS
middleware to the app to allow cross-origin requests.
1.3. Emit real-time data
Now, let's create a function that emits real-time data to the client using Socket.io. Add the following code to the server.js
file:
function emitServerData() {
const cpus = os.cpus();
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
const usedMemory = totalMemory - freeMemory;
io.emit('serverData', { cpus, totalMemory, usedMemory });
}
This function retrieves the CPU usage and memory usage data using the os
module and emits it to the client using the io.emit()
method.
1.4. Update the server to emit data periodically
Let's now update the server.js
file to call the emitServerData()
function periodically, so that it emits the server data to the client at regular intervals.
setInterval(() => {
emitServerData();
}, 1000);
This code calls the emitServerData()
function every second using the setInterval()
method.
The full code for the server.js
file should look something like this:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const os = require('os');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const port = process.env.PORT || 4000;
app.use(cors());
app.get('/', (req, res) => {
res.send('Server is up and running');
});
function emitServerData() {
const cpus = os.cpus();
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
const usedMemory = totalMemory - freeMemory;
io.emit('serverData', { cpus, totalMemory, usedMemory });
}
io.on('connection', (socket) => {
console.log(`Client connected: ${socket.id}`);
setInterval(emitServerData, 1000);
socket.on('disconnect', () => {
console.log(`Client disconnected: ${socket.id}`);
});
});
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
Step 2 - Set up the frontend
Now, we will create the frontend using Vue.js.
2.1. Install required packages.
In the root directory of your project, install the required packages for Vue.js using the following command:
npm install -g @vue/cli
This installs the @vue/cli
package globally, which provides the vue
command-line interface (CLI) for creating and managing
2.2. Create the Vue.js app
Use the following command to create a new Vue.js project:
vue create client
This command will prompt you to choose a preset. Select the default preset by pressing Enter
.
2.3. Set up the client to communicate with the server
Now, we need to set up the client to communicate with the server using Socket.io
. First, install the socket.io-client
package using the following command:
npm install socket.io client
Next, open the main.js
file located in the src
directory and add the following code to create a new instance of the socket.io-client
library and connect to the server:
import { createApp } from 'vue';
import App from './App.vue';
import io from 'socket.io-client';
const socket = io('http://localhost:4000', {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('connect', () => {
console.log('Connected to server');
});
createApp(App)
.mount('#app')
This code imports the socket.io-client
library and creates a new instance of it that connects to the server running on http://localhost:4000
.
2.4. Create the components
We will now create the components for our Vue.js app. In the src/components
directory, create two new files called ServerStatus.vue
and ServerData.vue
.
2.4.1. ServerStatus.vue
Add the following code to the ServerStatus.vue
file:
<template>
<div class="server-status">
<h1>Server Status</h1>
<div v-if="connected" class="status-connected">
<i class="fas fa-circle"></i>
<p>Connected</p>
</div>
<div v-else class="status-disconnected">
<i class="fas fa-circle"></i>
<p>Disconnected</p>
</div>
</div>
</template>
<script>
export default {
name: 'ServerStatus',
data() {
return {
connected: false
}
},
mounted() {
this.connectToServer();
},
methods: {
connectToServer() {
this.connected = true;
}
}
}
</script>
<style scoped>
.server-status {
margin-top: 50px;
text-align: center;
}
.status-connected {
display: flex;
align-items: center;
justify-content: center;
color: #28a745;
}
.status-disconnected {
display: flex;
align-items: center;
justify-content: center;
color: #dc3545;
}
</style>
This code defines a ServerStatus
component that displays whether the client is connected or disconnected from the server. It uses the socket
object we created earlier to detect the connection state.
2.4.2. ServerData.vue
Add the following code to the ServerData.vue
file:
<template>
<div class="server-data">
<h2>Server Data</h2>
<div class="server-info">
<div class="cpu-usage">
<h3>CPU Usage</h3>
<ul>
<li v-for="(cpu, index) in cpus" :key="index">{{ index }}: {{ cpu.model }}</li>
</ul>
</div>
<div class="memory-usage">
<h3>Memory Usage</h3>
<p>Total Memory: {{ totalMemory }} bytes</p>
<p>Used Memory: {{ usedMemory }} bytes</p>
<p>Free Memory: {{ freeMemory }} bytes</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'ServerData',
props: {
cpus: Array,
totalMemory: Number,
usedMemory: Number
},
computed: {
freeMemory() {
return this.totalMemory - this.usedMemory;
}
}
};
</script>
<style scoped>
.server-data {
margin-top: 50px;
}
.server-info {
display: flex;
justify-content: space-between;
}
.cpu-usage {
flex: 1;
text-align: left;
}
.memory-usage {
flex: 1;
text-align: right;
}
</style>
2.5. Create the server
We will now create the server using Node.js and Socket.io. Create a new file called server.js
in the root directory of the project and add the following code:
const os = require('os');
const io = require('socket.io')();
const PORT = 4000;
function collectServerData() {
const cpus = os.cpus();
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
const usedMemory = totalMemory - freeMemory;
return {
cpus,
totalMemory,
usedMemory
};
}
io.on('connection', (socket) => {
console.log('Client connected');
const interval = setInterval(() => {
const serverData = collectServerData();
socket.emit('serverData', serverData);
}, 1000);
socket.on('disconnect', () => {
clearInterval(interval);
console.log('Client disconnected');
});
});
io.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
This code imports the os
module to collect data about the server and the socket.io
library to handle real-time communication with the client. It defines a function called collectServerData()
that collects data about the server's CPUs and memory usage.It then creates a new socket.io
instance and listens for connections on port 4000. When a client connects, it starts sending server data to the client every second using a setInterval()
function. When the client disconnects, the interval is cleared.
2.6. Update the App.vue file
We will now update the App.vue
file to use the components we created earlier. Add the following code to the file:
<template>
<div id="app">
<ServerStatus />
<ServerData />
</div>
</template>
<script>
import ServerStatus from './components/ServerStatus.vue';
import ServerData from './components/ServerData.vue';
export default {
name: 'App',
components: {
ServerStatus,
ServerData
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
This code imports the ServerStatus
and ServerData
components we created earlier and adds them to the App
component.
2.7. Run the app
To run the app, open two terminals. In one terminal, navigate to the root directory of the project and run the following command to start the server:
node server.js
In the other terminal, navigate to the client directory and run the following command to start the Vue.js app:
npm run serve
This will start the Vue.js app and open it in your default web browser.
2.8. Test the app
If everything worked correctly, you should see the following on the Vue.js app:
- A
Server Status
component that displays whether the client is connected or disconnected from the server. - A
Server Data
component that displays information about the server's CPUs and memory usage.
If you open the browser console, you should see log messages indicating that the client has connected and disconnected from the server. Congratulations! You have created a server monitoring app using Vue.js and Node.js!
The full Code source is on GitHub so you can check it out there.
Posted on February 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
December 12, 2023