DEV Community

sadiul hakim
sadiul hakim

Posted on

Create a Real-Time digital clock with node and

At first setup your nodejs project.Then install and express.
This is going to be our folder structure...

folder structure

In index.js our code is going to be ...

import express from 'express';
import http from 'http';
import { Server } from '';

const app = express();
const expressServer = http.createServer(app);


const io = new Server(expressServer);

io.on('connect', function (socket) {
    console.log('a user is connected');

    setInterval(function () {
        let date = new Date().toLocaleTimeString()
    }, 1000)

    socket.on('disconnect', () => {
        console.log('user disconnected.')


app.get('/', (req, res, next) => {

expressServer.listen(4000, () => {
    console.log('server is listening.')
Enter fullscreen mode Exit fullscreen mode

and in index.html html code is going to be..

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <h1 id="time"></h1>
  <script src="/"></script>
    let socket = io();
    socket.on("message", function (msg) {
      document.getElementById("time").innerHTML = "";
      document.getElementById("time").innerHTML = msg;

Enter fullscreen mode Exit fullscreen mode

Now use should see your rea-time running clock in browser..



Top comments (0)