wayofthefuture
wayofthefuture

Reputation: 9455

How do professional Node libraries achieve asynchronous execution?

I've spent some time looking at Node Bcrypt and how they achieve the following asynchronous execution:

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
    // Store hash in your password DB.
});

They are performing computationally expensive tasks (salt generation) using an asynchronous callback. How are they doing this without blocking the main Node IO thread?

I've read about process.nextTick(), but this seems to operate similar to a setTimeout() in which you are distributing the CPU load over one thread (delaying the paying of the piper). Then there is childProcess.fork(), but I don't think they are using that as I can't find it anywhere in the GitHub repo.

Additionally, you have libraries such as Monk which achieves:

users.find({ name: 'Loki' }, '-bigdata').then(function () {
    // exclude bigdata field
})

There are no occurrences of fork() anywhere in this repo as well. I would think in order for Monk to offload that kind of processing would require a definite process fork versus some kind of recursive asynchronous callback.

I'm trying to implement this kind of asynchronous operation in my application, but would like to learn how the professionals are doing it. Does anyone know to achieve this?

Upvotes: 4

Views: 54

Answers (1)

Robin
Robin

Reputation: 7894

node.bcrypt uses the Node-GYP bindings to connect compiled C++ code (see the /src/ directory) to asynchronous Node functions.

So I believe that when that .hash function is called, the Node runtime will include the functions defined in the precompiled binary executable and run whatever computation is needed on another thread.

monk, on the other hand, depends on mongodb (NPM) (GitHub), which depends on mongodb-core (NPM) (GitHub), which uses Node's net module to create an asynchronous TCP client to talk to the MongoDB server process.

Upvotes: 3

Related Questions