🌐 Node-API
Node-API 是内置于 Node.js 的稳定 C API,允许 C/C++ 代码创建、读取和操作 JavaScript 值,就像这些值是由 JavaScript 本身创建的一样。它在 Node.js 8.0.0 中以实验性方式引入,并在 Node.js 8/10 期间变为稳定(不再需要标志)。
因为 Node-API 本身是 Node.js 的一部分,所以不需要额外安装。
🌐 Because Node-API is part of Node.js itself, it requires no additional installation.
🌐 Why Node-API instead of NAN?
在 Node-API 出现之前,原生插件开发的主要方法是 Node.js 的本地抽象 (NAN)。NAN 的工作方式是直接调用 V8 API,而该 API 会在每个主要 V8 版本中发生变化。这意味着基于 NAN 的插件在 Node.js 发布新 V8 版本时,经常需要重新编译——有时还需要更新。
🌐 Before Node-API, the dominant approach for native addon development was Native Abstractions for Node.js (NAN). NAN works by calling directly into the V8 API, which changes with every major V8 release. This means NAN-based addons often need to be recompiled - and sometimes updated - when Node.js ships a new V8 version.
Node-API 在稳定的接口后面抽象了 JavaScript 引擎。这为你提供了两个重要的保证:
🌐 Node-API abstracts the JavaScript engine behind a stable interface. This gives you two important guarantees:
- 向后兼容性 - 今天构建的模块将在未来所有版本的 Node.js 上运行,无需任何重新编译或代码更改。
- ABI 稳定性 - 因为 API 是 ABI 稳定的,已编译的
.node二进制文件本身可以在不同的 Node.js 版本中继续工作。
🌐 Common use cases
🌐 Wrapping an existing C/C++ library
编写本地插件最常见的原因是将现有的 C/C++ 库暴露给 JavaScript 开发者。Node-API 让你可以独立维护 C/C++ 代码,并以最小的努力保持 JavaScript 绑定的同步。
🌐 The most common reason to write a native addon is to expose an existing C/C++ library to JavaScript developers. Node-API lets you maintain your C/C++ code independently and keep the JavaScript bindings in sync with minimal effort.
🌐 Accessing OS resources
一些应用——例如使用 Electron 或 NW.js 构建的应用——需要访问 Node.js 未公开的系统 API。Node-API 提供了访问这些资源的接口。
🌐 Some applications - such as those built with Electron or NW.js - need access to system APIs that Node.js does not expose. Node-API provides the hooks to reach those resources.
🌐 Computationally intensive work
对于计算密集型任务,将热点路径用 C 或 C++ 编写,并通过 Node-API 从 JavaScript 调用它,可以获得显著的性能提升。与 JIT 编译的 JavaScript 不同,编译后的 C/C++ 二进制文件可以立即被 Node.js 使用,无需预热阶段。
🌐 For compute-heavy tasks, writing the hot path in C or C++ and calling it from JavaScript via Node-API can yield significant performance gains. Unlike JIT-compiled JavaScript, the compiled C/C++ binary is available to Node.js immediately without a warm-up phase.
Node-API 的一个重要的配套工具是 npm 包 node-addon-api。它在符合习惯的 C++ 对象模型中封装了 C API,减少了样板代码,并使常见模式——例如将 C++ 对象封装为 JavaScript 对象——更加符合使用习惯。它保留了 Node-API 的完整 ABI 稳定性保证。
🌐 An important companion to Node-API is the npm package node-addon-api. It wraps the C API in an idiomatic C++ object model, reducing boilerplate and making common patterns - like wrapping C++ objects as JavaScript objects - much more ergonomic. It retains the full ABI-stability guarantee of Node-API.
本网站上的大多数示例都使用 node-addon-api。
🌐 Most of the examples on this site use node-addon-api.