Node-API
Node-API 是用于构建原生插件的 API。它独立于底层的 JavaScript 运行时(例如 V8),并作为 Node.js 的一部分进行维护。该 API 在 Node.js 的各个版本之间将保持应用二进制接口(ABI)稳定。它旨在将插件与底层 JavaScript 引擎的变化隔离开,并允许为一个版本编译的模块在不重新编译的情况下运行在后续版本的 Node.js 上。插件的构建/打包方法与本文件中概述的方法/工具相同(如 node-gyp 等)。唯一的区别是原生代码使用的 API 集。Node-API 提供的函数将取代 V8 或 Node.js 的原生抽象 API 来使用。
【Node-API is an API for building native addons. It is independent from the underlying JavaScript runtime (e.g. 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 version to run on later versions of Node.js without recompilation. Addons are built/packaged with the same approach/tools outlined in this document (node-gyp, etc.). 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 the Node-API are used.】
创建和维护一个能够利用 Node-API 提供的 ABI 稳定性的插件,伴随着某些 实现考虑。
【Creating and maintaining an addon that benefits from the ABI stability provided by Node-API carries with it certain implementation considerations.】
要在上述“Hello world”示例中使用 Node-API,请将 hello.cc 的内容替换为以下内容。其他说明保持不变。
【To use Node-API in the above "Hello world" example, replace the content of
hello.cc with the following. All other instructions remain the same.】
// hello.cc using Node-API
#include <node_api.h>
namespace demo {
napi_value Method(napi_env env, napi_callback_info args) {
napi_value greeting;
napi_status status;
status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
if (status != napi_ok) return nullptr;
return greeting;
}
napi_value init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
if (status != napi_ok) return nullptr;
status = napi_set_named_property(env, exports, "hello", fn);
if (status != napi_ok) return nullptr;
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
} // namespace demo 可用的函数以及如何使用它们的说明,请参见 使用 Node-API 的 C/C++ 插件。
【The functions available and how to use them are documented in C/C++ addons with Node-API.】