Lance Shi
Lance Shi

Reputation: 1187

How to send events to client side via node js

I am using client side to send a post request to node js server to perform a long request. During the process, I want the server side can let the client side know how much work is already done and which step it is currently in. So I am wondering if there is a way for the server side to constantly sending events where the client side can receive. Something that can be received by $(document).on(). But It doesn't have to be limited in this way though.

It seems to be $.post only takes data from server side once. So how can I be able to continuously receive server side data after posting?

Upvotes: 3

Views: 4511

Answers (3)

vitor martins
vitor martins

Reputation: 51

Since you only want to send messages from the server to the client, you can also use Server-Sent Events (SSE).

You can setup listeners for the SSEs in your client-side script like this:

var serverEvents = new EventSource('http://localhost:8080/events');
serverEvents.addEventListener('message', function(event){
    console.log(event.data);
});

The browser will send a request to the URL provided when creating the new EventSource to establish a connection, then, from the server, you only need to send the messages in a particular format, for instance:

data: some data

data: {"name": "bobby"}

The individual messages must be separated by a pair of newline characters.

Node.js example:

const http = require('http');

const server = http.createServer((req, res) => {
  if( req.url === '/events'){
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Access-Control-Allow-Origin': '*'
    });
    setTimeout(() => {
      res.write('data: some data\n\n');
    }, 1000);
  }
});

server.listen(8080, '127.0.0.1');

Check out this link for more information: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

Upvotes: 5

Alongkorn
Alongkorn

Reputation: 4197

You need to use socket.io to do that.

See this example https://github.com/socketio/socket.io

Upvotes: 2

andreasonny83
andreasonny83

Reputation: 1213

The only way for creating a real-time communication between server and client side is using websockets. As already mentioned by @Nonemoticoner, the most famous websocket library is Socket.io

Upvotes: 2

Related Questions