你好世界
¥Hello world
这个 "你好世界" 示例是一个简单的插件,用 C++ 编写,相当于以下 JavaScript 代码:
¥This "Hello world" example is a simple addon, written in C++, that is the equivalent of the following JavaScript code:
module.exports.hello = () => 'world'; 首先,创建文件 hello.cc:
¥First, create the file hello.cc:
// hello.cc
#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(
isolate, "world", NewStringType::kNormal).ToLocalChecked());
}
void Initialize(Local<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
} // namespace demo 所有 Node.js 插件都必须按照以下模式导出初始化函数:
¥All Node.js addons must export an initialization function following the pattern:
void Initialize(Local<Object> exports);
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) NODE_MODULE 后面没有分号,因为它不是函数(参见 node.h)。
¥There is no semi-colon after NODE_MODULE as it's not a function (see
node.h).
module_name 必须与最终二进制文件的文件名匹配(不包括 .node 后缀)。
¥The module_name must match the filename of the final binary (excluding
the .node suffix).
在 hello.cc 示例中,初始化函数为 Initialize,插件模块名称为 addon。
¥In the hello.cc example, then, the initialization function is Initialize
and the addon module name is addon.
使用 node-gyp 构建插件时,使用宏 NODE_GYP_MODULE_NAME 作为 NODE_MODULE() 的第一个参数将确保最终二进制文件的名称将传给 NODE_MODULE()。
¥When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as
the first parameter of NODE_MODULE() will ensure that the name of the final
binary will be passed to NODE_MODULE().
用 NODE_MODULE() 定义的插件不能同时加载在多个上下文或多个线程中。
¥Addons defined with NODE_MODULE() can not be loaded in multiple contexts or
multiple threads at the same time.