你好世界


【Hello world】

这个“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.】