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.

    1. int main(int argc, char** argv) {
    2. argv = uv_setup_args(argc, argv);
    3. std::vector<std::string> args(argv, argv + argc);
    4. std::vector<std::string> exec_args;
    5. std::vector<std::string> errors;
    6. // Parse Node.js CLI options, and print any errors that have occurred while
    7. // trying to parse them.
    8. int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors);
    9. for (const std::string& error : errors)
    10. fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
    11. if (exit_code != 0) {
    12. return exit_code;
    13. }
    14. // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way
    15. // to create a v8::Platform instance that Node.js can use when creating
    16. // Worker threads. When no `MultiIsolatePlatform` instance is present,
    17. // Worker threads are disabled.
    18. std::unique_ptr<MultiIsolatePlatform> platform =
    19. MultiIsolatePlatform::Create(4);
    20. V8::InitializePlatform(platform.get());
    21. V8::Initialize();
    22. // See below for the contents of this function.
    23. int ret = RunNodeInstance(platform.get(), args, exec_args);
    24. V8::Dispose();
    25. V8::ShutdownPlatform();
    26. return ret;
    27. }