Node-API


Node-API(前称 N-API)是用于构建原生插件的 API。它独立于底层 JavaScript 运行时(例如 V8),并作为 Node.js 的一部分进行维护。该 API 在 Node.js 的各个版本之间将保持应用二进制接口(ABI)稳定。其目的是将插件与底层 JavaScript 引擎的变化隔离开来,并允许为一个主要版本编译的模块在 Node.js 的后续主要版本上运行,而无需重新编译。ABI 稳定性 指南提供了更深入的说明。

【Node-API (formerly N-API) is an API for building native Addons. It is independent from the underlying JavaScript runtime (for example, V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across versions of Node.js. It is intended to insulate addons from changes in the underlying JavaScript engine and allow modules compiled for one major version to run on later major versions of Node.js without recompilation. The ABI Stability guide provides a more in-depth explanation.】

插件的构建/打包采用了在标题为 C++ 插件 的部分中概述的相同方法/工具。唯一的区别在于本地代码使用的 API 集。Node-API 中可用的函数取代了 V8 或 Node.js 的原生抽象 API。

【Addons are built/packaged with the same approach/tools outlined in the section titled C++ Addons. The only difference is the set of APIs that are used by the native code. Instead of using the V8 or Native Abstractions for Node.js APIs, the functions available in Node-API are used.】

Node-API 暴露的 API 通常用于创建和操作 JavaScript 值。其概念和操作通常对应于 ECMA-262 语言规范中指定的思想。这些 API 具有以下特性:

【APIs exposed by Node-API are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the ECMA-262 Language Specification. The APIs have the following properties:】

  • 所有 Node-API 调用都会返回类型为 napi_status 的状态码。该状态码表示 API 调用是成功还是失败。
  • API 的返回值通过输出参数传递。
  • 所有 JavaScript 值都被抽象为一个名为 napi_value 的不透明类型。
  • 在出现错误状态码时,可以使用 napi_get_last_error_info 获取更多信息。更多信息可以在错误处理部分 错误处理 中找到。