<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tanisha G</title>
    <description>The latest articles on DEV Community by Tanisha G (@tanishag).</description>
    <link>https://dev.to/tanishag</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1214162%2F39d36ae9-5e87-4d33-bd65-68725ab4170a.png</url>
      <title>DEV Community: Tanisha G</title>
      <link>https://dev.to/tanishag</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tanishag"/>
    <language>en</language>
    <item>
      <title>Implementation of Cluster -Node.js</title>
      <dc:creator>Tanisha G</dc:creator>
      <pubDate>Tue, 09 Jan 2024 14:53:04 +0000</pubDate>
      <link>https://dev.to/tanishag/implementation-of-cluster-nodejs-3eb4</link>
      <guid>https://dev.to/tanishag/implementation-of-cluster-nodejs-3eb4</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RWtpIS4L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bogq4aclgodd5vpgi5li.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RWtpIS4L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bogq4aclgodd5vpgi5li.jpg" alt="Image description" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we all know node.js is a popular runtime environment that offers scalability and high performance. To handle tasks at the process level, the "Cluster" module was introduced.&lt;/p&gt;

&lt;p&gt;Do not get confused between cluster and work thread,worker threads are to run javascript in parallel,Cluster helps in running the process in parallel by creating multiple instances of nodejs &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benefits of clustering&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Improves the performance:&lt;/strong&gt;&lt;br&gt;
Clustering enables your Node.js application to process more concurrent requests by making use of many CPU cores. This leads to faster reaction times and enhanced performance in general, particularly in applications with heavy traffic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Scalability:&lt;/strong&gt;&lt;br&gt;
Horizontal scaling—which involves adding more machines to your infrastructure and dividing the workload among them—is made possible by clustering. You may easily scale your application as it grows by adding more worker processes across many servers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Fault Tolerance:&lt;/strong&gt;&lt;br&gt;
If a bug or other problem causes one of the worker processes to crash, the remaining worker processes can continue processing incoming requests. This makes your application more fault tolerant and guarantees that it will continue to function even if one or more of its components fail.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now let's dive into executing an API with and without clustering and load testing results.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a simple js file with the express server running on a dynamic port&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const port = 3000;
app.listen(port, () =&amp;gt; {
console.log(`App listening on port ${port}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;now install the cluster and load test npm's&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/cluster"&gt;cluster&lt;/a&gt; - npm link&lt;br&gt;
&lt;a href="https://www.npmjs.com/package/loadtest"&gt;loadtest&lt;/a&gt; - npm link&lt;br&gt;
"os" is a nodejs core module&lt;/p&gt;

&lt;p&gt;In the below code "os" gives information about our operating system and next have to check whether the process is primary or not then cluster.fork() is responsible for creating the worker processes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cluster = require("cluster");
const totalCPUs = require("os").availableParallelism();

if (cluster.isPrimary) {
  console.log(`Number of CPUs is ${totalCPUs}`);
  console.log(`Primary ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i &amp;lt; totalCPUs; i++) {
    cluster.fork();
  }

  cluster.on("exit", (worker, code, signal) =&amp;gt; {
    console.log(`worker ${worker.process.pid} died`);
    console.log("Let's fork another worker!");
    cluster.fork();
  });
} else {
  const app = express();
  console.log(`Worker ${process.pid} started`);

  app.get("/", (req, res) =&amp;gt; {
    res.send("Hello World!");
  });

  app.get("/api/:n", function (req, res) {
    let n = parseInt(req.params.n);
    let count = 0;

    if (n &amp;gt; 5000000000) n = 5000000000;

    for (let i = 0; i &amp;lt;= n; i++) {
      count += i;
    }

    res.send(`Final count is ${count}`);
  });

  app.listen(port, () =&amp;gt; {
    console.log(`App listening on port ${port}`);
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now lets do the load testing&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; loadtest http://localhost:3000/api/50000000 -n 1000 -c 100
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;below are the results based on the above-mentioned load testing pattern just compare the rps,mean time&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ loadtest http://localhost:3000/api/50000000 -n 1000 -c 100
Requests: 9 (2%), requests per second: 2, mean latency: 2388.1 ms
Requests: 82 (16%), requests per second: 16, mean latency: 2554.7 ms
Requests: 82 (16%), requests per second: 15, mean latency: 7957.6 ms
Requests: 100 (20%), requests per second: 4, mean latency: 5470.7 ms
Requests: 162 (32%), requests per second: 12, mean latency: 10967.5 ms
Requests: 109 (22%), requests per second: 5, mean latency: 10633.8 ms
Requests: 153 (31%), requests per second: 9, mean latency: 11488.6 ms
Requests: 200 (40%), requests per second: 8, mean latency: 11290.9 ms
Requests: 201 (40%), requests per second: 10, mean latency: 11753.6 ms
Requests: 234 (47%), requests per second: 7, mean latency: 11896.6 ms
Requests: 221 (44%), requests per second: 4, mean latency: 11999.5 ms
Requests: 300 (60%), requests per second: 13, mean latency: 12040.1 ms
Requests: 300 (60%), requests per second: 16, mean latency: 11784 ms
Requests: 308 (62%), requests per second: 2, mean latency: 11705.5 ms
Requests: 309 (62%), requests per second: 2, mean latency: 11520.4 ms
Requests: 385 (77%), requests per second: 15, mean latency: 11541.5 ms
Requests: 373 (75%), requests per second: 13, mean latency: 11684.4 ms
Requests: 400 (80%), requests per second: 3, mean latency: 11566.5 ms
Requests: 409 (82%), requests per second: 7, mean latency: 12009.4 ms
Requests: 450 (90%), requests per second: 10, mean latency: 12009.5 ms
Requests: 444 (89%), requests per second: 7, mean latency: 12018 ms

Target URL:          http://localhost:3000/api/50000000
Max requests:        1000
Concurrent clients:  200
Running on cores:    2
Agent:               none

Completed requests:  1000
Total errors:        0
Total time:          58.25 s
Mean latency:        10472.6 ms
Effective rps:       17

Percentage of requests served within a certain time
  50%      11675 ms
  90%      12033 ms
  95%      12076 ms
  99%      12155 ms
 100%      12191 ms (longest request)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;next result is when we hit the API when cluster is enabled&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ loadtest http://localhost:3000/api/50000000 -n 1000 -c 100
Requests: 139 (28%), requests per second: 28, mean latency: 2377.8 ms
Requests: 139 (28%), requests per second: 28, mean latency: 2343.4 ms
Requests: 278 (56%), requests per second: 28, mean latency: 3438.2 ms
Requests: 281 (56%), requests per second: 28, mean latency: 3441.2 ms
Requests: 405 (81%), requests per second: 25, mean latency: 3855.3 ms
Requests: 410 (82%), requests per second: 26, mean latency: 3864.8 ms

Target URL:          http://localhost:3000/api/50000000
Max requests:        1000
Concurrent clients:  200
Running on cores:    2
Agent:               none

Completed requests:  1000
Total errors:        0
Total time:          18.563 s
Mean latency:        3318.1 ms
Effective rps:       54

Percentage of requests served within a certain time
  50%      3515 ms
  90%      3924 ms
  95%      3961 ms
  99%      3992 ms
 100%      4004 ms (longest request)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To sum up, Node.js clustering is an essential method for realizing the full potential of your server-side apps. In addition to enhancing performance, it offers a scalable and resilient base, guaranteeing that your applications can adapt to growing traffic levels and still function well in the face of unforeseen difficulties. &lt;/p&gt;

&lt;p&gt;I’ll keep on adding more topics as I learn.Thankyou&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Getting Started with GraphQL - Nodejs</title>
      <dc:creator>Tanisha G</dc:creator>
      <pubDate>Wed, 22 Nov 2023 06:04:25 +0000</pubDate>
      <link>https://dev.to/tanishag/getting-started-with-graphql-nodejs-2g5f</link>
      <guid>https://dev.to/tanishag/getting-started-with-graphql-nodejs-2g5f</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--C2jZryqh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktqzgtygvovdydx8plft.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--C2jZryqh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktqzgtygvovdydx8plft.png" alt="Image description" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is GraphQL&lt;/strong&gt;&lt;br&gt;
As per the documentation, "GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But why GraphQL?&lt;/strong&gt;&lt;br&gt;
Imagine a scenario where the client needs user data but only a username list should be the output. The next one is where the client needs only the user's phone number and the requirement list goes on. Now in the situations mentioned above would you like to write different APIs or send the whole user's data (unnecessary/extra data) over network calls?&lt;/p&gt;

&lt;p&gt;This is where GraphQL comes into the picture by using GraphQL queries you can do db actions/queries and return the output directly&lt;/p&gt;

&lt;p&gt;Now let's dive into the implementation part, I am going to use the Apollo server to set up Graphql&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i @apollo/server body-parser express axios
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have set up async startServer function which includes declaring and starting the server, and &lt;strong&gt;app.use&lt;/strong&gt; indicates that any query for the URL /graphql is going to be handled by the server(Apollo)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const server = require("express")
const bodyParser = require("body-parser")
const { ApolloServer} = require("@apollo/server")
const axios = require("axios")
const { expressMiddleware } = require("@apollo/server/express4")
const cors = require("cors")
var app = server()
const startServer = async () =&amp;gt; {
 app.use(cors())
 app.use(bodyParser.json())
 const server = new ApolloServer({})
 await server.start()
 app.use(
    "/graphql",
    expressMiddleware(server)
  )
  app.listen(8000, () =&amp;gt; {
    console.log("port started on 8000")
  })
}
startServer()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but the Apollo server has certain restrictions where typeDefs and resolvers are compulsory for the server to start. Now let's see what are typeDefs and resolvers&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;typeDefs&lt;/strong&gt; are nothing but schema along with type declarations&lt;br&gt;
Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    type Post{
      id:ID (ID denotes id field can be of type anything)
      title:String! (! Dentos that field can not be null )
      body:String 
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;resolvers&lt;/strong&gt; are the ones that give out the result for the queries made.&lt;/p&gt;

&lt;p&gt;Let's take up a dummy example for a deeper understanding, user and todo are two different schemas where each user can have multiple todos, and every todo is linked to a particular user by userId.Time to declare some typeDefs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const server = new ApolloServer({
 typeDefs: `
    type User{
      name: String!
    }
    type Todo{
      id: ID!
      title: String!
    }
  type Query{
    getTodos:[Todo]
    getUsers:[User]
  }`,
 resolvers:{
 Query: {
   getTodos: async () =&amp;gt; (await 
   axios.get("https://jsonplaceholder.typicode.com/todos")).data,
   getUsers: async () =&amp;gt; (await 
   axios.get("https://jsonplaceholder.typicode.com/users")).data,
}
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;type Query indicates the query function name and the data return format, so now in the resolvers also Query should be declared and the action to take place inside the function being called should be written.&lt;/p&gt;

&lt;p&gt;getTodos is going to fetch all the todo lists in the array format and getUsers is going to fetch all the users in array format as declared in type Query.&lt;/p&gt;

&lt;p&gt;Run your server on &lt;a href="http://localhost:8000/graphql"&gt;http://localhost:8000/graphql&lt;/a&gt; below mentioned UI will be given by Apollo only,in getTodos query I have mentioned the fields that I want to be in the output but you cannot send any random field, the field being requested should be declared in the schema:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HsG5ui6f--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brecyndpdzqplosj8u18.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HsG5ui6f--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brecyndpdzqplosj8u18.png" alt="Image description" width="800" height="395"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;getUsers:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wZSlewP0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv71s54ecb8pcridlx5e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wZSlewP0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv71s54ecb8pcridlx5e.png" alt="Image description" width="800" height="398"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now let's make the query a little more complex&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I want to get all the todos along with the user name who has created it&lt;/em&gt;&lt;br&gt;
change the schema and resolvers accordingly&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; type Todo{
      id:ID!
      title:String!
      user:User
      userId:String!
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;resolvers{
 Todo: {
        user: async (todo) =&amp;gt; (await axios.get(`https://jsonplaceholder.typicode.com/users/${todo.userId}`)).data
      },
Query:{remains the same}
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Todo in the resolvers indicates that whenever there is a query Todo needs to get the user details to whom the todo belongs based on userId meanwhile in the schema I have added a user field that will hold the User details which refers to the User schema which is already declared.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--U-6w1uSp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ealrv6ce4kcw72sl4ws5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--U-6w1uSp--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ealrv6ce4kcw72sl4ws5.png" alt="Image description" width="800" height="397"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Challenege&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Write a function to fetch only particular todo based on the id field. Let me know the query and resolver functions in the comments below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we saw what is graphql, why there is a need for it, and a simple example of graphql query in the upcoming blog I will be explaining about mutations i.e. updation/deletion/creation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rT0WQZEk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3buo96tjesgmbolmzj6h.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rT0WQZEk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3buo96tjesgmbolmzj6h.gif" alt="Image description" width="200" height="200"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>graphql</category>
      <category>query</category>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Server-Sent Events -Node.js</title>
      <dc:creator>Tanisha G</dc:creator>
      <pubDate>Mon, 20 Nov 2023 08:24:35 +0000</pubDate>
      <link>https://dev.to/tanishag/server-sent-events-nodejs-1mk3</link>
      <guid>https://dev.to/tanishag/server-sent-events-nodejs-1mk3</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--25yHlx51--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0ppc6ywdoy8cao8qy0u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--25yHlx51--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0ppc6ywdoy8cao8qy0u.png" alt="Image description" width="311" height="162"&gt;&lt;/a&gt;&lt;em&gt;Staying ahead in the ever-changing field of web development entails embracing technologies that enable real-time communication between clients and servers. Server-Sent Events (SSE) is one such technology that has gained traction. When used in conjunction with Node.js, SSE opens up a new world of possibilities for developing responsive, interactive, and data-driven online apps. In this blog post, we will dive into SSE with nodejs using express&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is SSE?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;SSE is a straightforward and efficient technique for transmitting real-time changes from the server to the client using a single HTTP connection.&lt;/p&gt;

&lt;p&gt;SSE enables the server to deliver changes to the client as soon as they become available, reducing the need for constant polling or complicated WebSocket configurations. This technology is suitable for providing real-time updates, such as news feeds, sports scores, or monitoring systems.&lt;/p&gt;

&lt;p&gt;We can delete the &lt;strong&gt;short polling&lt;/strong&gt; strategy (making requests from the front end at regular intervals).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SSE Format&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Event&lt;/strong&gt;— The” event ” field is optional and used to specify the type of event being sent.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data&lt;/strong&gt;— The “ data ” field consists of the payload of the event. Multiple “data” lines, each representing a different piece of data, can be inserted within a single SSE message.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Id&lt;/strong&gt;— The “ id ” field is optional and can be used to assign a unique identifier to the event. This can assist clients in keeping track of which events they have received.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retry&lt;/strong&gt;— The “retry” field is also optional and specifies the reconnection time (in milliseconds) that the client should wait before attempting to reconnect if the connection is lost.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;event: myEvent
data: This is some data
data: More data for the event
id: 123
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Server Side Implementation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a server.js file in your root directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express')
const app = express()
const cors = require("cors")
app.use(cors())
app.use(express.json())


function serverSentEevnts(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })

  let sseId = new Date().toLocaleDateString()

  //in regular interval it needs to be sent
  setInterval(() =&amp;gt; {
    writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
  }, 5000)
  writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
}
function writeServerSendEvent(res, sseId, data) {
  res.write('id: ' + sseId + '\n');
  res.write("data: new server event " + data + '\n\n');
}

app.get("/talk", (req, res) =&amp;gt; {
  serverSentEevnts(req, res)
})

app.listen(5000, () =&amp;gt; {
  console.log("starting port on 5000")
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Client Side Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
   &amp;lt;head&amp;gt;
      &amp;lt;meta charset="utf-8" /&amp;gt;
   &amp;lt;/head&amp;gt;
   &amp;lt;body&amp;gt;
      &amp;lt;input type="button" id="stopButton" value="Stop Listening"/&amp;gt;
      &amp;lt;hr/&amp;gt;
      &amp;lt;div id="content"&amp;gt;&amp;lt;/div&amp;gt;
      &amp;lt;script&amp;gt;
         var source = new EventSource('http://localhost:5000/talk');
         source.addEventListener('open', function(e) {
         document.getElementById('content').innerHTML += 'Connections to the server established..&amp;lt;br/&amp;gt;';
         }, false);
         source.onmessage = function(e) {
         document.getElementById('content').innerHTML += e.data + '&amp;lt;br/&amp;gt;';
         };
         document.getElementById('stopButton').onclick=function(){
         document.getElementById('content').innerHTML += 'Listening to server events stopped..&amp;lt;br/&amp;gt;';
         source.close();
         }
      &amp;lt;/script&amp;gt;
   &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mention this in the package.json file to run it locally.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "start": "http-server -p 8080"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should be able to open &lt;a href="http://localhost:8080"&gt;http://localhost:8080&lt;/a&gt; in your browser and watch the events. Pressing the button should stop listening to the server send events.&lt;/p&gt;

&lt;p&gt;By now you will be able to see a successful working model of SSE in nodejs&lt;/p&gt;

&lt;p&gt;I’ll keep on adding more topics as I learn.Thankyou&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
      <category>serversentevents</category>
    </item>
  </channel>
</rss>
