设置每个进程状态
¥Setting up per-process state
Node.js 需要一些每个进程的状态管理才能运行:
¥Node.js requires some per-process state management in order to run:
-
Node.js CLI 选项 的参数解析,
¥Arguments parsing for Node.js CLI options,
-
V8 每个进程要求,例如
v8::Platform
实例。¥V8 per-process requirements, such as a
v8::Platform
instance.
下面的示例展示了如何设置这些。一些类名分别来自 node
和 v8
C++ 命名空间。
¥The following example shows how these can be set up. Some class names are from
the node
and v8
C++ namespaces, respectively.
int main(int argc, char** argv) {
argv = uv_setup_args(argc, argv);
std::vector<std::string> args(argv, argv + argc);
std::vector<std::string> exec_args;
std::vector<std::string> errors;
// Parse Node.js CLI options, and print any errors that have occurred while
// trying to parse them.
int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors);
for (const std::string& error : errors)
fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
if (exit_code != 0) {
return exit_code;
}
// Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way
// to create a v8::Platform instance that Node.js can use when creating
// Worker threads. When no `MultiIsolatePlatform` instance is present,
// Worker threads are disabled.
std::unique_ptr<MultiIsolatePlatform> platform =
MultiIsolatePlatform::Create(4);
V8::InitializePlatform(platform.get());
V8::Initialize();
// See below for the contents of this function.
int ret = RunNodeInstance(platform.get(), args, exec_args);
V8::Dispose();
V8::ShutdownPlatform();
return ret;
}