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::Platforminstance.
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;}
