1e41f4b71Sopenharmony_ci# Node-API简介
2e41f4b71Sopenharmony_ci
3e41f4b71Sopenharmony_ci## 场景介绍
4e41f4b71Sopenharmony_ci
5e41f4b71Sopenharmony_ciOpenHarmony Node-API是基于Node.js 8.x LTS的[Node-API](https://nodejs.org/docs/latest-v8.x/api/n-api.html)规范扩展开发的机制,为开发者提供了ArkTS/JS与C/C++模块之间的交互能力。它提供了一组稳定的、跨平台的API,可以在不同的操作系统上使用。
6e41f4b71Sopenharmony_ci
7e41f4b71Sopenharmony_ci本文中如无特别说明,后续均使用Node-API指代OpenHarmony Node-API能力。
8e41f4b71Sopenharmony_ci
9e41f4b71Sopenharmony_ci> **说明:**
10e41f4b71Sopenharmony_ci>
11e41f4b71Sopenharmony_ci> OpenHarmony Node-API与Node.js 8.x LTS的Node-API规范的接口异同点,详见[Node-API参考](../reference/native-lib/napi.md)
12e41f4b71Sopenharmony_ci
13e41f4b71Sopenharmony_ci一般情况下OpenHarmony应用开发使用ArkTS/JS语言,但部分场景由于性能、效率等要求,比如游戏、物理模拟等,需要依赖使用现有的C/C++库。Node-API规范封装了I/O、CPU密集型、OS底层等能力并对外暴露ArkTS/JS接口,从而实现ArkTS/JS和C/C++的交互。主要场景如下:
14e41f4b71Sopenharmony_ci
15e41f4b71Sopenharmony_ci- 系统可以将框架层丰富的模块功能通过ArkTS/JS接口开放给上层应用。
16e41f4b71Sopenharmony_ci
17e41f4b71Sopenharmony_ci- 应用开发者也可以选择将一些对性能、底层系统调用有要求的核心功能用C/C++封装实现,再通过ArkTS/JS接口使用,提高应用本身的执行效率。
18e41f4b71Sopenharmony_ci
19e41f4b71Sopenharmony_ci## Node-API的组成架构
20e41f4b71Sopenharmony_ci
21e41f4b71Sopenharmony_ci**图1** Node-API的组成架构
22e41f4b71Sopenharmony_ci  
23e41f4b71Sopenharmony_ci![napi_mechanism](figures/napi_mechanism.png)
24e41f4b71Sopenharmony_ci
25e41f4b71Sopenharmony_ci- Native Module:开发者使用Node-API开发的模块,用于在ArkTS侧导入使用。
26e41f4b71Sopenharmony_ci
27e41f4b71Sopenharmony_ci- Node-API:实现ArkTS与C/C++交互的逻辑。
28e41f4b71Sopenharmony_ci
29e41f4b71Sopenharmony_ci- ModuleManager:Native模块管理,包括加载、查找等。
30e41f4b71Sopenharmony_ci
31e41f4b71Sopenharmony_ci- ScopeManager:管理napi_value的生命周期。
32e41f4b71Sopenharmony_ci
33e41f4b71Sopenharmony_ci- ReferenceManager:管理napi_ref的生命周期。
34e41f4b71Sopenharmony_ci
35e41f4b71Sopenharmony_ci- NativeEngine:ArkTS引擎抽象层,统一ArkTS引擎在Node-API层的接口行为。
36e41f4b71Sopenharmony_ci
37e41f4b71Sopenharmony_ci- ArkCompiler ArkTS Runtime:ArkTS运行时。
38e41f4b71Sopenharmony_ci
39e41f4b71Sopenharmony_ci## Node-API的关键交互流程
40e41f4b71Sopenharmony_ci
41e41f4b71Sopenharmony_ci**图2** Node-API的关键交互流程
42e41f4b71Sopenharmony_ci  
43e41f4b71Sopenharmony_ci![process_napi](figures/process_napi.png)
44e41f4b71Sopenharmony_ci
45e41f4b71Sopenharmony_ciArkTS和C++之间的交互流程,主要分为以下两步:
46e41f4b71Sopenharmony_ci
47e41f4b71Sopenharmony_ci1. **初始化阶段**:当ArkTS侧在import一个Native模块时,ArkTS引擎会调用ModuleManager加载模块对应的so及其依赖。首次加载时会触发模块的注册,将模块定义的方法属性挂载到exports对象上并返回该对象。
48e41f4b71Sopenharmony_ci
49e41f4b71Sopenharmony_ci2. **调用阶段**:当ArkTS侧通过上述import返回的对象调用方法时,ArkTS引擎会找到并调用对应的C/C++方法。
50