CodeBlanks Logo Icon CodeBlanks

node-addon-api

Learn the node-addon-api C++ wrapper.

node-addon-api

node-addon-api is a C++ wrapper built on top of N-API. Instead of raw N-API C calls you work with C++ classes, which makes the code more readable and less error-prone. The node-addon-api header is included in a single line.

An addonWrapper(className, methods) function models this wrapper idea: it takes a class name and a methods list, returning {class, methods, wrapper: 'node-addon-api'}. In real node-addon-api a C++ class is bound to a JS class with Napi::ObjectWrap. Here we model it in JS to understand what the wrapper does: it hides complex C calls behind class methods. The output is node-addon-api, the wrapper's name.

The wrapper pattern

The core pattern of node-addon-api is: you define a C++ class, declare its methods, then expose it to JS. addonWrapper models this by returning an object. The .wrapper property tells which wrapper is used.

Example: addonWrapper('Calculator', ['add', 'subtract']) returns {class: 'Calculator', methods: ['add', 'subtract'], wrapper: 'node-addon-api'}. .wrapper is 'node-addon-api'. This pattern represents a real addon's structure with a simple object: class name, methods and a wrapper. Although the real code is C++, the structure is the same: a class, a method list and a binding mechanism. console.log(...wrapper) verifies which wrapper is used.

Practice Write the wrapper function

Write function addonWrapper(className, methods). Return {class: className, methods: methods, wrapper: 'node-addon-api'}. Print console.log(addonWrapper('Calculator', ['add', 'subtract']).wrapper).

Starter code

index.js
// Write an addonWrapper function
// Takes a class name and a methods list
// Returns {class, methods, wrapper: 'node-addon-api'}
// Print the wrapper value
// write here

Sample solution

index.js
function addonWrapper(className, methods) {
  return {class: className, methods: methods, wrapper: 'node-addon-api'};
}
console.log(addonWrapper('Calculator', ['add', 'subtract']).wrapper);

Expected output

node-addon-api

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Return the methods list

Question
function addonWrapper(className, methods) { return {class: className, methods: ____, wrapper: 'node-addon-api'}; }
Answer
function addonWrapper(className, methods) { return {class: className, methods: methods, wrapper: 'node-addon-api'}; }

Explanation: The methods parameter is returned directly.

2 Match each concept to its description

Term Meaning
node-addon-api C++ wrapper
Napi::ObjectWrap Binds a C++ class to JS
wrapper The wrapper name
methods The method list

3 What does addonWrapper(...).wrapper return?

index.js
addonWrapper('Calculator', ['add']).wrapper
  • 'Calculator'
  • 'add'
  • 'node-addon-api' Correct answer
  • ['add']

Explanation: The .wrapper property returns 'node-addon-api'.

All lessons in Expert