How to Build a C/C++ Node.js Add-on with N-API: A Step-by-Step Guide

Learn how to create a C/C++ extension for Node.js using the stable N-API ABI, covering environment setup with node-gyp, writing the module code for a simple multiply-by-two function, building the add-on, and running it across platforms with minimal compilation hassle.

Node Underground
Node Underground
Node Underground
How to Build a C/C++ Node.js Add-on with N-API: A Step-by-Step Guide

C/C++ extensions have been part of the Node.js ecosystem for a long time.

For most Node.js developers, writing C/C++ extensions is a significant challenge. In addition to language barriers, developers must understand V8 and NAN (Native Abstractions for Node.js) APIs/ABIs, which were not designed for Node.js scenarios and are therefore unfriendly. Moreover, C/C++ extensions directly depend on the stability of V8 and NAN interfaces, making compilation and maintenance costly.

Node 8.x introduced N-API to address this problem by providing a stable ABI abstraction layer, dramatically reducing cross-platform compilation costs for C/C++ extensions. It also allows the underlying VM with the same ABI to be swapped seamlessly, such as switching from V8 to Node-ChakraCore.

The article’s author, Schahriar SaffarShargh, presents a detailed example of writing a C/C++ extension that implements a “multiply by 2” function. The steps are:

Install node-gyp and prepare the build environment, configuring binding.gyp .

Write module.c to implement the multiply-by-2 logic.

Build and run the newly created extension.

The article provides complete code and step-by-step explanations, making the process approachable for beginners. Click “Read the original article” to start coding.

Backend DevelopmentNode.jsC++N-API
Node Underground
Written by

Node Underground

No language is immortal—Node.js isn’t either—but thoughtful reflection is priceless. This underground community for Node.js enthusiasts was started by Taobao’s Front‑End Team (FED) to share our original insights and viewpoints from working with Node.js. Follow us. BTW, we’re hiring.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.