C++ 嵌入器 API#

Node.js 提供了許多 C++ API,可用於在其他 C++ 軟體中透過 Node.js 環境執行 JavaScript。

這些 API 的文件可以在 Node.js 原始碼樹的 src/node.h 中找到。除了 Node.js 暴露的 API,V8 嵌入器 API 也提供了一些必要的概念。

因為將 Node.js 作為嵌入式庫使用不同於編寫由 Node.js 執行的程式碼,所以破壞性變更不遵循典型的 Node.js 棄用策略,並且可能在每個 semver-major 版本中發生,恕不另行通知。

嵌入應用的示例#

以下章節將概述如何使用這些 API 從零開始建立一個應用程式,該應用程式將執行與 node -e <code> 等效的操作,即獲取一段 JavaScript 並在 Node.js 特定環境中執行它。

完整程式碼可以在 Node.js 原始碼樹中找到。

設定程序級狀態#

Node.js 需要一些程序級狀態管理才能執行:

  • 為 Node.js CLI 選項解析引數,
  • 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);
  // Parse Node.js CLI options, and print any errors that have occurred while
  // trying to parse them.
  std::unique_ptr<node::InitializationResult> result =
      node::InitializeOncePerProcess(args, {
        node::ProcessInitializationFlags::kNoInitializeV8,
        node::ProcessInitializationFlags::kNoInitializeNodeV8Platform
      });

  for (const std::string& error : result->errors())
    fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
  if (result->early_return() != 0) {
    return result->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(), result->args(), result->exec_args());

  V8::Dispose();
  V8::DisposePlatform();

  node::TearDownOncePerProcess();
  return ret;
} 

設定例項級狀態#

Node.js 有一個“Node.js 例項”的概念,通常被稱為 node::Environment。每個 node::Environment 都與以下內容相關聯:

  • 恰好一個 v8::Isolate,即一個 JS 引擎例項,
  • 恰好一個 uv_loop_t,即一個事件迴圈,
  • 多個 v8::Context,但只有一個主 v8::Context,以及
  • 一個 node::IsolateData 例項,其中包含可由多個 node::Environment 共享的資訊。嵌入器應確保 node::IsolateData 僅在共享同一個 v8::Isolatenode::Environment 之間共享,Node.js 不會執行此檢查。

為了設定一個 v8::Isolate,需要提供一個 v8::ArrayBuffer::Allocator。一種可能的選擇是 Node.js 的預設分配器,可以透過 node::ArrayBufferAllocator::Create() 建立。當外掛使用 Node.js C++ Buffer API 時,使用 Node.js 分配器可以帶來輕微的效能最佳化,並且對於在 process.memoryUsage() 中跟蹤 ArrayBuffer 記憶體是必需的。

此外,如果正在使用 MultiIsolatePlatform 例項,則用於 Node.js 例項的每個 v8::Isolate 都需要向該例項註冊和登出,以便平臺知道為 v8::Isolate 排程的任務使用哪個事件迴圈。

輔助函式 node::NewIsolate() 會建立一個 v8::Isolate,用一些 Node.js 特定的鉤子(例如 Node.js 錯誤處理程式)來設定它,並自動將其註冊到平臺。

int RunNodeInstance(MultiIsolatePlatform* platform,
                    const std::vector<std::string>& args,
                    const std::vector<std::string>& exec_args) {
  int exit_code = 0;

  // Setup up a libuv event loop, v8::Isolate, and Node.js Environment.
  std::vector<std::string> errors;
  std::unique_ptr<CommonEnvironmentSetup> setup =
      CommonEnvironmentSetup::Create(platform, &errors, args, exec_args);
  if (!setup) {
    for (const std::string& err : errors)
      fprintf(stderr, "%s: %s\n", args[0].c_str(), err.c_str());
    return 1;
  }

  Isolate* isolate = setup->isolate();
  Environment* env = setup->env();

  {
    Locker locker(isolate);
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);
    // The v8::Context needs to be entered when node::CreateEnvironment() and
    // node::LoadEnvironment() are being called.
    Context::Scope context_scope(setup->context());

    // Set up the Node.js instance for execution, and run code inside of it.
    // There is also a variant that takes a callback and provides it with
    // the `require` and `process` objects, so that it can manually compile
    // and run scripts as needed.
    // The `require` function inside this script does *not* access the file
    // system, and can only load built-in Node.js modules.
    // `module.createRequire()` is being used to create one that is able to
    // load files from the disk, and uses the standard CommonJS file loader
    // instead of the internal-only `require` function.
    MaybeLocal<Value> loadenv_ret = node::LoadEnvironment(
        env,
        "const publicRequire ="
        "  require('node:module').createRequire(process.cwd() + '/');"
        "globalThis.require = publicRequire;"
        "require('node:vm').runInThisContext(process.argv[1]);");

    if (loadenv_ret.IsEmpty())  // There has been a JS exception.
      return 1;

    exit_code = node::SpinEventLoop(env).FromMaybe(1);

    // node::Stop() can be used to explicitly stop the event loop and keep
    // further JavaScript from running. It can be called from any thread,
    // and will act like worker.terminate() if called from another thread.
    node::Stop(env);
  }

  return exit_code;
}