设置每个进程的状态


Node.js 需要一些每个进程的状态管理才能运行:

  • 为 Node.js 命令行选项解析的参数,
  • V8 每个进程要求,例如 v8::Platform 实例。

下面的示例展示了如何设置这些。 一些类名分别来自 nodev8 C++ 命名空间。

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;
  // 解析 Node.js 命令行选项,
  // 并打印尝试解析它们时发生的任何错误。
  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;
  }

  // 创建 v8::Platform 实例。
  // `MultiIsolatePlatform::Create()` 是一种创建 v8::Platform 实例的方法,Node.js 在创建时可以使用它
  // 工作线程。当没有 `MultiIsolatePlatform` 实例时,
  // 工作线程被禁用。
  std::unique_ptr<MultiIsolatePlatform> platform =
      MultiIsolatePlatform::Create(4);
  V8::InitializePlatform(platform.get());
  V8::Initialize();

  // 此函数的内容见下文。
  int ret = RunNodeInstance(platform.get(), args, exec_args);

  V8::Dispose();
  V8::ShutdownPlatform();
  return ret;
}

Node.js requires some per-process state management in order to run:

  • Arguments parsing for Node.js CLI options,
  • V8 per-process requirements, such as a v8::Platform instance.

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;
}