目录

Node-API Overview

When to Use

HarmonyOS Node-API is a mechanism extended from the Node-API specification of Node.js 18.x LTS. It provides the interaction capability between ArkTS/JS and C/C++ modules, and offers a set of stable, cross-platform APIs that can be used on different operating systems.

Unless otherwise specified, Node-API in this document refers to HarmonyOS Node-API.

For details about the differences between HarmonyOS Node-API and the Node-API specification of Node.js 18.x LTS, see Node-API.

Generally, ArkTS/JS is used for HarmonyOS application development. However, in compute-intensive scenarios, such as games and physical simulations, the existing C/C++ libraries are required to meet the requirements for performance and efficiency. Node-API encapsulates I/O, CPU-intensive, and OS underlying capabilities and exposes these capabilities in the form of C APIs. It uses the C/C++ module registration mechanism to mount properties and methods to ArkTS/JS objects to implement interaction between ArkTS/JS and C/C++. Node-API provides the following benefits:

Node-API Architecture

Figure 1 Node-API architecture

Key Interaction Process of Node-API

Figure 2 Key interaction process of Node-API

The interaction between ArkTS and C++ consists of the following two steps:

  1. Initialization: When a native module is imported to ArkTS, the ArkTS engine calls the ModuleManager to load the .so file and dependencies of the module. When the module is loaded for the first time, the module registration is triggered. Then, the method properties defined by the module are embedded to an exports object and the object is returned.

  2. Invocation: When an ArkTS method is called using the exports object, the ArkTS engine locates and calls the embedded C/C++ method.