Question

I've seen process.binding('...') many times while researching through the node.js source code on github.

Can anybody explain me what this function does?

Was it helpful?

Solution

This function returns internal module, like require. It's not public, so you shouldn't rely on it in your code, but you can use it to play with node's low level objects, if you want to understand how things work.

For example, here timer_wrap binding is registered. It exports Timer constructor. In lib/timers.js it's imported

OTHER TIPS

It's a feature that essentially goes out and grab the C++ feature and make it available inside the javascript . Take this example process.binding('zlib') that is used in zlib

This is essentially going out and getting the zlib C++ object and then it's being used the rest of the time in the javascript code.

So when you use zlib you're not actually going out and grabbing the C++ library, you're using the Javascript library that wraps the C++ feature for you.

It makes it easier to use

process.binding connects the javascript side of Node.js to the C++ side of the Node.js. C++ side of node.js is where a lot of the internal work of everything that node does, is actually implemented. So a lot of your code relies upon ultimately C++ code. Node.js is using the power of C++.

Here is an example:

const crypto=require(“crypto”)
const start=Date.now()
crypto.pbkdf2(“a”, “b”, 100000,512,sha512,()=>{
console.log(“1”:Date.now()-start)
})

Crypto is a built-in module in Node.js for hashing and saving passwords. This is how we implement it in Node.js but actual hashing process takes place in C++ side of node.js.

process.binding("crypto") is gonna take this process to the exporters of src directory where is c++ world of Node.js. In this side of Node.js, V8 is going to translate the node.js values that we place inside of our different programs like a boolean or a function or an object and translate it into their C++ equivalents.

After Javascript code is translated to C++, libuv is going to take place and will do all heavy calculations to execute above code in the c++ side, outside the event loop, in thread pool.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top