Jaan
Jaan

Reputation: 25

How to queue the post request in Node.js?

Current post request:

app.post('/rImage', rawBody, function (req, res) {
// ---- check here, if this process is running ? ----
  var data = req.rawBody;
  var escapedData = data.replace(/([<>|&^])/g, "\^$1"); // Windows CMD escaping
  exec('cscript /nologo C:/PS/Automation/render.vbs C:/PS/Automation/image.jsx"'+escapedData + '"',
    function (error, stdout, stderr)  {
      console.log('stdout: ' + escapedData);

      if(error !== null) {
        console.log('exec error: ' + error);
      }
      res.send(stdout);
      //request finished
    });
});

How could I implement a queue system to this, so that the next request fires off when the last one is finished?

Thanks in adnvance!

Upvotes: 1

Views: 2141

Answers (1)

Anton Harald
Anton Harald

Reputation: 5944

There might be libraries for this. However, you could hack it like this:

var queue = [];
var active = false;
var check = function() {
   if (!active && queue.length > 0) {
      var f = queue.shift();
      f();
   }
}

app.post("..", body, function(req, res) {
   queue.push(function() {
      active = true;

      exec("yourprogram arg1 arg2..", function() {
          // this is the async callback
          active = false;
          check();
      });
   });
   check();
});

Here's a fiddle that shows the functionality: https://jsfiddle.net/fc15afw5/1/

Upvotes: 4

Related Questions