Nodejs: What does `process.binding` mean?
Asked Answered
E

3

84

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?

Eastlake answered 4/6, 2014 at 16:33 Comment(0)
F
72

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

Forelimb answered 4/6, 2014 at 16:39 Comment(1)
process.binding seems to change to internalBinding from v11.xEspalier
F
20

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

Flaming answered 24/10, 2017 at 11:1 Comment(1)
Thanks for the brief and crisp explanation.Eat
D
8

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.

Doze answered 10/6, 2019 at 7:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.