🌐 Your First Project
在开始之前,确保你已经安装了所有必要的前置条件和工具,并阅读Node-API 项目的结构以了解所有 node-addon-api 项目共有的常见布局和配置文件。
🌐 Before you start, make sure you've got all the necessary prerequisites and tools installed, and read Anatomy of a Node-API project to understand the common layout and configuration files shared by all node-addon-api projects.
本教程在 C++ 封装层使用 node-addon-api。
🌐 This tutorial uses node-addon-api at the C++ wrapper level.
🌐 Creating a project
获得一个可运行项目的最快方法是从 node-addon-examples 仓库复制 Hello World 示例:
🌐 The quickest way to get a working project is to copy the Hello World example from the node-addon-examples repository:
git clone https://github.com/nodejs/node-addon-examples.git
cp -r node-addon-examples/src/1-getting-started/a-first-project/node-addon-api hello-world
cd hello-world
npm install或者,手动设置项目:
🌐 Alternatively, set up the project manually:
mkdir hello-world
cd hello-world
npm init -y
npm install node-addon-api然后创建下面描述的源文件。一旦项目设置完成,验证一切是否正常运行:
🌐 Then create the source files described below. Once the project is set up, verify everything works:
npm testhello_world.cc 可能是你能写出的最简单且有用的 Node-API 文件。
该文件定义了一个 C++ Method 函数,该函数接受一个 Napi::CallbackInfo& 参数。这个 info 对象提供对 JavaScript 环境的访问,包括从 JavaScript 传入的任何参数。
🌐 The file defines a C++ Method function that takes a single Napi::CallbackInfo& argument. This info object provides access to the JavaScript environment, including any arguments passed in from JavaScript.
info的行为像 JavaScript 的参数数组。
Method 使用 info 来获取一个 Napi::Env,然后创建并返回一个值为 "world" 的 Napi::String。
Init 函数注册了此模块的单个导出:名称 "HelloWorld" 映射到 Method 函数。
🌐 The Init function registers the single export from this module: the name "HelloWorld" maps to the Method function.
底部的 NODE_API_MODULE 宏确保在模块加载时调用 Init。
🌐 The NODE_API_MODULE macro at the bottom ensures Init is called when the module is loaded.
binding.js 加载已编译的二进制文件并重新导出其内容。二进制文件的唯一导出是 HelloWorld 函数。
test_binding.js 使用 require 从 binding.js 加载 HelloWorld 函数。testBasic 函数调用它并验证结果。
🌐 Conclusion
本项目展示了一个最小的 Node-API 模块,该模块导出一个函数。接下来可以尝试的一些内容:
🌐 This project demonstrates a minimal Node-API module that exports a single function. Some things to try next:
- 在你的调试器中运行
test_binding.js。逐步执行代码,并观察你对 C++ 代码创建的 JavaScript 对象的可见性。 - 将
test_binding.js修改为直接引用编译后的二进制文件,而不是通过binding.js。在调试器中逐步执行并注意区别。 - 修改
hello_world.cc以读取从 JavaScript 传入的参数。node-addon-api示例 是很好的参考。