-1

I have a websocket server in node.js which allows users to solve a given puzzle.

I also have a code that generates random puzzle for about 20 seconds. In the meantime I still want to handle new connections/disconnects, but this synchronous code blocks the event loop.

Here's the simplified code:

io.on('connection', socket => {
//
});

io.listen(port);

setInterval(function() {
    if (game.paused)
        game.loadRound();
}, 1000);

loadRound runs about 20 seconds, that blocks all connections and setInterval itself

What would be the correct way to run this code without blocking event loop?

Herokiller
  • 2,891
  • 5
  • 32
  • 50

1 Answers1

1

You have three basic choices:

  1. Redesign loadRound() so that it doesn't block the event loop. Since you've shared none of the code for it, we can't advise on the feasibility of that, but if it's doing any I/O, then it does not need to block the event loop. Even if it's all just CPU work, it could be designed to do its job in small chunks to allow the event loop some cycles, but often that's more work to redesign it that way than options 2 and 3 below.

  2. Move loadRound() to a worker thread (new in node.js) and communicate the result back via messaging.

  3. Move loadRound() to a separate node.js process using the child_process module and communicate the result back via any number of means (stdio, messaging, etc...).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • I ended up moving it to separate process writing to file and reading from that file (without using child_process). is that a bad practice? – Herokiller Aug 04 '19 at 01:14
  • @Herokiller - How do you start and manage the other process? How do you communicate with it? child_process would be used if you want to start and manage the other process from your node.js app and it has some built-in comunications. But, you don't have to do it that way. – jfriend00 Aug 04 '19 at 01:52
  • @Herokiller - If all you're doing is read and writing to files and you use proper asynchronous file I/O calls, you should be able to do that in-process without a whole lot of issue. For node.js, the actual file I/O is done uses a thread pool (if you use asynchronous file I/O calls). But, you don't show us that actual code so we can't really offer you any specific suggestions on that code. – jfriend00 Aug 04 '19 at 01:57