2

When executing a long-processing task in a request callback function with NodeJS,

handler = function(req, res) {
    // long CPU processing task (non I/O), e.g. compute N digits of Pi 
}

net.createServer(handler);

or

var express = require('express');
var app = express();
app.get('/', function (req, res) {
    // long processing task
});
app.listen(3000);

is it still the same tread (then is it blocking?) or not?

Note: I know it's probably not good practice to do a long processing task here, but I'm curious about how NodeJS handles it.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • No. Nodejs is single-threaded. It is just smart at prioritizing and putting requests on hold. – RaphaMex Jun 07 '18 at 19:06
  • @RaphaMex So if the callback takes 10 seconds, no other request can be processed in the meantime? (Again, I know it's not good practice but it was just to know how it works). – Basj Jun 07 '18 at 19:08
  • Just to add more on @RaphaMex comment - it's nicelly called an event loop and you can read more about it here https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ – Owi Jun 07 '18 at 19:08
  • @JJJ this question focuses a lot about IO, here I mean doing long computations in general (e.g. computing Pi digits). – Basj Jun 07 '18 at 19:12
  • 2
    "So if the callback takes 10 seconds, no other request can be processed in the meantime?" Correct, assuming the 10 seconds is actually all spent evaluating JavaScript code and not doing any I/O of any type or any other asynchronous operations. If you have long running JavaScript tasks you should start another process to run it and wait for it asynchronously (EG. using child_process). If you need to handle large numbers of concurrent requests you should have a cluster of processes. – Paul Jun 07 '18 at 19:13
  • If you bother to read the duplicate the top answer discusses all kinds of operations. – JJJ Jun 07 '18 at 19:14
  • @Paulpro Ok, so this seems to be the answer, feel free to post it as an answer. – Basj Jun 07 '18 at 19:16
  • @Paulpro could you give an example of callback (involving I/O) that would take 10 seconds but still would *not* block the event loop / NodeJS thread? – Basj Jun 07 '18 at 19:18
  • 1
    @Basj There are many things that could do that. `fs.readFile` on a sufficiently large file (although you would probably want to stream a file that large unless there is a reason you need the entire thing in memory at once). Using the `request` module to make a few remote API calls is another example. The simplest example, albiet not involving I/O, would be something like `setTimeout( _ => res.send(), 10000 );` – Paul Jun 07 '18 at 19:24

1 Answers1

0

No way it creates threads. I quote from here:

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient

So, in a few words, Node is just too good managing concurrence

Gustavo Topete
  • 1,246
  • 1
  • 9
  • 15