Stream Data to Charts in Real-Time using Websockets and Express
Tags: websockets, charts, node, datavisualization
Published: 2024-01-29 12:14:06

In today's dynamic digital landscape, the demand for real-time data visualization is ever-growing. Whether it's monitoring live traffic on a website, tracking stock market fluctuations, or analyzing sensor data in IoT devices, the ability to visualize data as it streams in can provide invaluable insights and drive informed decision-making. In this blog post, we'll use Websockets and [Express](https://expressjs.com/) to stream real-time data and transform it into visually appealing charts with the help of [CanvasJS](https://canvasjs.com/javascript-charts/).

### **Setting Up the Environment**

First, let's set up our development environment. Make sure you have Node.js and npm installed on your system. Then, create a new directory for our project and initialize it with a **`package.json`** file:

```jsx
mkdir real-time-charts-websocket-app
cd real-time-charts-websocket-app
npm init -y
```

Next, install the necessary dependencies:
```js
npm install express socket.io
```

### **Implementing the Server**
Now, let's create the server-side application using Express and integrate Websockets with socket.io

```jsx
/* server.js */
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Serve static files from the 'public' directory
app.use(express.static('public'));

let  y = 1000;

// Handle websocket connections
io.on('connection', (socket) => {
    console.log('A client has connected');    
});

// Sending data to the server every 2 seconds
setInterval(() => {
    y += Math.round(100 + Math.random() *(-100-100));
    io.emit('data', JSON.stringify({
        value: y
    }))
}, 2000)

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
```

You can customize the above as per your requirement for sending data to Websocket clients e.g. broadcasting the data to a particular pool of users. Also, in the above, I am creating random data and sending it to the client on every interval. But in real-world scenario, this data can be coming from Iot devices or some third-party APIs.
### **Creating the Client-Side Interface**

Now that we have our server set up, let's create the client-side interface where we'll display the real-time data using CanvasJS charts.

```jsx
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Real-Time Charts with CanvasJS</title>
    <script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
  </head>
  <body>
    <div id="chartContainer" style="height: 300px; width: 100%"></div>

    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();

      // Initialize CanvasJS chart
      const chart = new CanvasJS.Chart('chartContainer', {
        theme: 'light2',
        title: {
          text: 'Real-Time Data Visualization with Websockets',
        },
        data: [
          {
            type: 'spline',
            dataPoints: [],
          },
        ],
      });

      // Listen for incoming data
      socket.on('data', (data) => {
        data = JSON.parse(data);
        chart.options.data[0].dataPoints.push({ y: data.value });
        chart.render();
      });
    </script>
  </body>
</html>
```

We will be storing index.html inside public folder.

### Running the Application

With both the server and client-side code in place, let's start our application by running the server:

```jsx
node server.js
```

Now, open your web browser and navigate to **`http://localhost:3000`**. You should see a real-time chart updating with data streamed from the server.

### **Conclusion**

In this blog post, we've explored how to achieve real-time data visualization by streaming data with Websockets and Express, and then visualizing it using CanvasJS. By combining these powerful technologies, developers can create engaging and interactive data visualization applications that provide valuable insights to users in real time. Whether it's monitoring live analytics, tracking IoT sensor data, or visualizing financial markets, the possibilities for real-time data visualization are endless with Websockets, Express, and CanvasJS.

{% embed https://stackblitz.com/edit/plotting-real-time-data-websockets-canvasjs?embed=1&file=server.js %}