-1

I need a huge help or advice, please. I need to stress the Node.js server - just high the CPU - because I need to test a monitoring tool of the market.
The cenario is: I need a button to start the stress and other to stop it.
I tried use the Loadtest, but when it started it didn't stop programatically, only if I close it manually (if anyone has any advice about it, please!). Then I tried to do a simple while loop, because I thought I could stop it, but it didn't worked..

var shouldRun = true;

app.get("/cpuup", (req, res) => {
  var result = 0;
  while (shouldRun) {
    result += Math.random() * Math.random();
  }
  return result;
});

app.get("/cpudown", (req, res) => {
  shouldRun = false;
});

Could anyone give me advice about another way to do it or I can't stop an asynchronous thread? Thanks!

barbs
  • 172
  • 1
  • 9
  • 1
    You can't stop this code because it is part of the ["event loop"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop). This isn't a direct answer to your question, but watching this video - [Philip Roberts: What the heck is the event loop anyway?](https://youtu.be/8aGhZQkoFbQ) - should help provide more of a foundational understanding of what is going on in your application. – romellem Sep 26 '18 at 14:33
  • @romellem thank you! :) – barbs Sep 26 '18 at 14:51

1 Answers1

-1

Synchronous while loop is blocking, shouldRun = false will never be reached.

Blocking operations should be avoided in applications that needs concurrency like web server.

Relying on global flag variable is questionable, but this can be fixed by using async loop. Route handler isn't supposed to return anything, returned value should be send as a response instead if needed.

As explained in this answer, Express middlewares and route handlers should handle promise rejections to provide proper error handling, in the case of async function this requires try..catch:

app.get("/cpuup", async (req, res, next) => {
  try {
    var result = 0;
    while (shouldRun) {
      result += Math.random() * Math.random();
      await null; // a delay
    }
    res.send('' + result);
  } catch (err) {
    next(error);
  }
});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • If you downvote a correct answer, a good thing would be to provide a comment how it can be improved. – Estus Flask Sep 26 '18 at 18:53
  • I can't downvote. Besides this isn't the correct answer. I asked how to stop an asynchronous thread. – barbs Sep 26 '18 at 23:21
  • @barbs It explains how to stop *asynchronous* thread. The one listed in the OP it is *blocking* and cannot be stopped from another request. – Estus Flask Sep 27 '18 at 05:44