Node.js
Binding
Learn JS-to-C++ binding.
Binding
Binding is the act of connecting a JS function to native code. The native side calls the function, the JS side returns the result. A bindFunction(name, fn) function models this: it records the function's name and parameter count (arity).
fn.length gives the number of declared parameters of a JS function. Example: for function(a, b) { return a + b; }, .length is 2. bindFunction('add', add) returns {name: 'add', arity: 2}. During binding the native side uses this info: it calls by name and checks arity. This is the foundation of the bridge between native and JS. The output is add: 2; name and parameter count on one line.
What is arity?
Arity is the number of parameters a function expects. In JavaScript you get it with fn.length. Example: for function(a, b) {...}, .length is 2. For functions with default parameters .length counts only the non-default parameters.
Arity matters during binding: the native side does not call with the wrong count. bindFunction('add', add) records add's arity as 2; the native side reads it. console.log(bindFunction('add', add).name + ': ' + bindFunction('add', add).arity) prints add: 2. This is the most basic check of binding: name and parameter count. In real N-API actual parameters are fetched with napi_get_cb_info but arity is still useful.
Exercise Write the binding function
Write function bindFunction(name, fn). Return {name: name, arity: fn.length}. Define const add = function(a, b) { return a + b; }. Print console.log(bindFunction('add', add).name + ': ' + bindFunction('add', add).arity).
Show example solution
function bindFunction(name, fn) {
return {name: name, arity: fn.length};
}
const add = function(a, b) { return a + b; };
console.log(bindFunction('add', add).name + ': ' + bindFunction('add', add).arity);
Test yourself
-
Match each concept to its description
- Binding
- Bridge between JS and native
- fn.length
- Parameter count
- arity
- Name for the parameter count
- name
- Function name
-
What is function(a, b) { return a + b; }.length?
function(a, b) { return a + b; }.length
Show answer
2 — Two parameters (a, b) are declared, .length is 2.
-
Complete the arity value
return {name: name, arity: fn.____};
Show answer
return {name: name, arity: fn.length};
Next lesson: Callback