Nodejs: What does `process.binding` mean?

JavascriptC++node.jsV8Undocumented Behavior

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

when node.js runs this function, actually inside of this function, it passes all the arguments to the PBKDF2() function which is the c++ code. this function does all the calculations and returns the result. this is how PBKDF imported to the javascript side of the node.js

const {PBKDF2}=process.binding(“crypto”)

So this is how javascript side of node.js is connected to the c++ side of node.js. in the c++ side of node.js, V8 is going to translate the node.js values into their c++ equivalents.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlaconbassView Question on Stackoverflow
Solution 1 - JavascriptvkurchatkinView Answer on Stackoverflow
Solution 2 - JavascriptMohamed Ben HEndaView Answer on Stackoverflow
Solution 3 - JavascriptYilmazView Answer on Stackoverflow