A Real-Time Chat Application TypeScript Project Using Node.js as a Server

Typescript and Node.js have gained in popularity among programmers over the years. TypeScript is a typed JavaScript superset. In contrast to Node.js, TypeScript aids in the development process by guaranteeing that you are free of defects and small errors. JavaScript is a server-side execution platform for JavaScript programming that is open-source. This tutorial will create a Real-time chat application TypeScript Project using JavaScript with Node.js as a server.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Prerequisites

  • To Install Node.js go to node.js official website. After installing, enter the command “node -v” to check if the node is installed properly.
  • Run npm init to produce the package.json file for Node.js. This will prompt you to ask a series of questions about your project. This instructs you on how to set up a typical Node.js project.
  • Typescript dependencies are required to set up Typescript with Node.js. Run the following command to install the Typescript compiler package:

npm install -g typescript  

  • The Typescript compiler will be installed worldwide with the command above. This implies that each project you create on your computer can use Typescript dependencies without reinstalling the Typescript package.
  • To see if the compiler is installed, type tsc —version. 

Starting the TypeScript Project

Firstly, you need to create a new folder

mkdir Chat-App

Go to Visual Studio Code and open the folder created above with the name ChatApp.

Inside the folder create a new file called Index.html. In this index.html File, you must write the code to create the user interface.  

<html>

    <head>

        <title>IO chat</title>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <script src="https://code.jquery.com/jquery-2.2.4.min.js"

                integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="

                crossorigin="anonymous"></script>

        <script src="/socket.io/socket.io.js"></script>

        <style>

            body{

                margin-top:30px;

            }

        </style>

    </head>

    <body>

       <div class="container">

           <div class="row">

                <div class="col-md-4">

                    <div class="well">

                        <h3>Online Users</h3>

                        <ul class="list-group" id="users"></ul>

                    </div>    

                </div>

                <div class="col-md-8">

                     <div class="chat" id="chat"></div>  

                     <form id="messageForm">

                         <div class="form-group">

                              <label>Enter Message</label>

                              <textarea class="form-control" id="message"></textarea>

                              </br>

       <input type="submit" class="btn btn-primary"value="Send Message"/>              

                         </div>

                     </form>

                </div>

           </div>

       </div> 

    </body>

</html>

TypeScript_Project_User_Interface.

In this code, you use CDN that is Bootstrap CDN and jQuery CDN.

A CDN is a network of servers that caches content close to where each end-user accesses the internet via a web-enabled device and distributes it worldwide from an "origin" server. The content they request is first stored on the origin server, then replicated and stored in other locations as needed.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

The most popular CSS framework for creating responsive and mobile-first websites is Bootstrap. Bootstrap 5 is the most recent version of the Bootstrap framework. Bootstrap is a free and open-source CSS framework for front-end web development that is responsive and mobile-first. It includes design templates for typography, forms, buttons, navigation, and other interface elements based on CSS and JavaScript.

jQuery is a feature-rich, short, and compact JavaScript library. With an easy-to-use API that works across various browsers, it simplifies HTML document traversal and manipulation, event handling, animation, and Ajax, with a blend of adaptability and extensibility.

Next, you will create a new file called server.js in the same folder. Then you will go to the terminal and run these commands.

  • npm install socket.io

Socket.IO is a library that allows the browser and server to communicate in real-time, bidirectionally, and depending on events. It consists of the following components: a Node.js server (this repository) and a browser-based JavaScript client library (or a Node.js client).

  • npm install express

Express is a Node.js web application framework that offers a comprehensive range of functionality for both web and mobile apps.

In the server.js file write the below code:

var express = require("express");

const { listen } = require("socket.io");

var app = express();

var server = require("http").createServer(app);

var io = require("socket.io")(server);

users = [];

connections = [];

server.listen(3000);

app.get("/", function (req, resp) {

  //route for localhost:3000/

  resp.sendFile(__dirname + "/index.html");

})

io.sockets.on("connection", function (socket) {

    //when client connects to server

    connections.push(socket); //add plug details to custom array

    console.log("connected : %s socket connected", connections.length); //curr connections

    socket.on("disconnect", function (data) {

      //client disc. frm server

      connections.splice(connections.indexOf(socket), 1); //delete plug details

      console.log("Dsiconnected : %s socket connected", connections.length); //curr connections

    });

    socket.on("send message", function (data) {

        console.log(data);

        io.sockets.emit("new message", { msg: data });

      });

}); 

console.log('server is listening')

After writing this code, save the file. Then go to the terminal and run the command.

“Node server” Output will be shown as the server is listening. Then go to the browser and run on localhost:3000, and the chat application is open and ready to use.

TypeScript_Project_ChatApp.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Next Steps

Hope that this TypeScript Project- Chat Application has provided you with a foundational grasp of TypeScript and NodeJS. Course certification will be advantageous if you learn these technologies and possibly work as a developer or programmer.

If you wish to learn these programming languages and work as a developer or programmer, course certification will benefit you. Enroll in the Full Stack Web Developer - MEAN Stack Master's program to learn typescript.

If you have any specific queries on TypeScript Project, please let us know. Please share any recommendations or questions about using TypeScript projects with NodeJS in the comments section. Our experts will respond as quickly as possible!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.