你好世界


🌐 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) // N.B.: no semi-colon, this is not a function
} // namespace demo 

在大多数平台上,以下 Makefile 可以让我们入手:

🌐 On most platforms, the following Makefile can get us started:

NODEJS_DEV_ROOT ?= $(shell dirname "$$(command -v node)")/..
CXXFLAGS = -std=c++23 -I$(NODEJS_DEV_ROOT)/include/node -fPIC -shared -Wl,-undefined,dynamic_lookup
hello.node: hello.cc
	$(CXX) $(CXXFLAGS) -o $@ __CONTENT__#x3C; 

然后运行以下命令将编译并运行代码:

🌐 Then running the following commands will compile and run the code:

$ make
$ node -p 'require("./hello.node").hello()'
world 

要与 npm 生态系统集成,请参阅 构建 部分。

🌐 To integrate with the npm ecosystem, see the Building section.

AltStyle によって変換されたページ (->オリジナル) /