title: Node.js listen to session variable change and trigger server-sent event
body: <p>I am writing a webapp, using express.js.</p>
  
  <p>My webapp achieves the following</p>
  
  <ol>
  <li>User posts 100 json objects</li>
  <li>Each json object is processed via a service call</li>
  <li>Once the service call is completed, a session variable is incremented</li>
  <li>On incrementation of the session variable, a server side event must be sent to the client to update the progress bar</li>
  </ol>
  
  <p>How do i achieve listening on a session variable change to trigger a server-sent event?</p>
  
  <p>Listening to a variable change is not the only solution I seek?</p>
  
  <p>I need to achieve sending a server-sent event once a JSON object is processed.</p>
  
  <p>Any appropriate suggestion is welcome</p>
  
  <p>Edit (based on Alberto Zaccagni's comment)</p>
  
  <p>My code looks like this:</p>
  
  <pre><code>function processRecords(cmRecords,requestObject,responseObject)
  {
      for (var index = 0; index &lt; cmRecords.length; index++) 
      {
          post_options.body = cmRecords[index];
          request.post(post_options,function(err,res,body)
          {
              if(requestObject.session.processedcount)
                  requestObject.session.processedcount = requestObject.session.processedcount + 1;
              else
                  requestObject.session.processedcount = 1;
  
              if(err)
              {
                  appLog.error('Error Occured %j',err);
              }
              else
              {
                  appLog.debug('CMResponse: %j',body);
              }
  
              var percentage = (requestObject.session.processedcount / requestObject.session.totalCount) * 100;
  
              responseObject.set('Content-Type','text/event-stream');
              responseObject.json({'event':'progress','data':percentage});
          });
      };
  
  
  }
  </code></pre>
  
  <ol>
  <li><p>When the first record is updated and a server side event is triggered using the responseObject (express response object)</p></li>
  <li><p>When the second record is updated and I try triggering a server side event using the same responseObject. I get an error saying cannot set header to a response that has already been sent</p></li>
  </ol>