DEV Community

millow-stack
millow-stack

Posted on

How to make a simple chat-app in Node.Js

Ever wondered how it would have been if you could talk to your friends on the app that you made!For me it would have been something next to happiness. Basically, we are going to use Express framework and some basics of File Management.

First things First

Now we will set a proper environment for our code.

  • Make a folder with name of your choice.
  • Add the following files into it:
    • main.js
    • index.html
    • msg.htm -Open the cmd and type, npm init

main.js

var express = require('express');
var fs = require('fs');

var app = express();

app.get('/', function(req, res){
    res.sendFile(__dirname+'/index.html');
})

app.get('/msg', function(req, res){
    res.sendFile(__dirname+'/msg.htm');
})

app.post('/', function(req, res){
    fs.appendFile(__dirname+'/msg.htm', '\n<li>'+req.query.nm+' : '+req.query.mg+'</li>', (err)=>{
        console.log(err)
    });
    res.redirect('/');
})

app.listen(80);
Enter fullscreen mode Exit fullscreen mode

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Chat</title>
    <style type="text/css">
        input[type = hidden]{
            display: none;
        }
        input[type = text]{
            width: 95%;
            height: 25px;
            border: 0.25px solid black;
            outline: none;
        }
        iframe{
            width: 95%;
            height: calc(100% - 5px);
            border: 0.25px double black;
        }
        form{
            text-align: center;
        }
    </style>
</head>
<body>
    <form method="post" acction="/">
        <input type="hidden" hidden id="nm" name="nm">
        <input type="text" name="mg">
        <iframe src="msg">Unsupported</iframe>  
    </form>
    <script type="text/javascript">
        if (document.cookie){
            document.querySelector('#nm').value = document.cookie;
        } else {
            document.cookie = prompt('Your nickname here:');
            document.querySelector('#nm').value = document.cookie;
        }
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

msg.htm

<style type="text/css">
    li{
        border-bottom: 0.25px solid #333;
    }
</style>
<script type="text/javascript">
    setInterval(500, function(){
        window.reload()
    })
</script>
Enter fullscreen mode Exit fullscreen mode

You can find your result on localhost

Top comments (0)