萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js 原生擴充開發指南:用 C++ 為 JavaScript 構建高效能橋接模組

Node.js 透過 N-API (舊版為 NAN/V8 API) 允許編寫 C++ 原生模組,將計算密集型任務、系統級 API 呼叫、現有 C/C++ 庫封裝為 JavaScript 可呼叫的模組。本文以 node-notify (GTK+ 桌面通知) 為例,完整示範從專案結構、C++ 綁定代碼、建構配置到 JavaScript 呼叫的全流程。

專案結構

node-notify/
├── build/                 # 編譯產出 .node 檔案
├── demo/
│   └── demo.js            # 測試腳本
├── src/
│   └── node_gtknotify.cpp # C++ 綁定核心代碼
└── binding.gyp            # node-gyp 建構配置 (取代舊版 wscript)

JavaScript 介面設計 (demo.js)

// 載入編譯產出的原生模組
var notify = require('./build/Release/gtknotify.node'); // 路徑視建構輸出而定

// API 設計:建構函式 + 屬性設定 + 發送方法
var notification = new notify.Notification();
notification.title = '通知標題';
notification.icon = 'emblem-default'; // 參考 /usr/share/icons/gnome/16x16
notification.send('通知內容訊息');

C++ 綁定核心實現 (src/node_gtknotify.cpp)

1. 引入標頭與命名空間

#include 
#include 
#include 
#include 
#include 

using namespace v8;
using namespace node;

2. 繼承 ObjectWrap 類別

class GtkNotify : public ObjectWrap {
public:
  static void Init(Local exports);
  GtkNotify();
  ~GtkNotify();

private:
  // 建構函式回呼
  static void New(const FunctionCallbackInfo& args);
  // 屬性存取器
  static void GetTitle(Local property, const PropertyCallbackInfo& info);
  static void SetTitle(Local property, Local value, const PropertyCallbackInfo& info);
  static void GetIcon(Local property, const PropertyCallbackInfo& info);
  static void SetIcon(Local property, Local value, const PropertyCallbackInfo& info);
  // 原型方法
  static void Send(const FunctionCallbackInfo& args);

  // 內部狀態
  NotifyNotification* notification_;
  std::string title_;
  std::string icon_;
};

3. 模組初始化與導出

Persistent GtkNotify::constructor;

void GtkNotify::Init(Local exports) {
  Isolate* isolate = exports->GetIsolate();

  // 定義建構函式模板
  Local tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "Notification").ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1); // 一個內部欄位指向 C++ 實例

  // 定義屬性存取器
  tpl->InstanceTemplate()->SetAccessor(
    String::NewFromUtf8(isolate, "title").ToLocalChecked(),
    GetTitle, SetTitle
  );
  tpl->InstanceTemplate()->SetAccessor(
    String::NewFromUtf8(isolate, "icon").ToLocalChecked(),
    GetIcon, SetIcon
  );

  // 定義原型方法
  NODE_SET_PROTOTYPE_METHOD(tpl, "send", Send);

  constructor.Reset(isolate, tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked());
  exports->Set(
    String::NewFromUtf8(isolate, "Notification").ToLocalChecked(),
    tpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked()
  );
}

4. 方法實現細節

void GtkNotify::New(const FunctionCallbackInfo& args) {
  Isolate* isolate = args.GetIsolate();
  if (args.IsConstructCall()) {
    // new Notification()
    GtkNotify* obj = new GtkNotify();
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // 直接呼叫 Notification() 轉為建構呼叫
    Local cons = Local::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(isolate->GetCurrentContext()).ToLocalChecked());
  }
}

void GtkNotify::SetTitle(Local property, Local value, const PropertyCallbackInfo& info) {
  Isolate* isolate = info.GetIsolate();
  GtkNotify* obj = ObjectWrap::Unwrap(info.Holder());
  String::Utf8Value utf8(isolate, value);
  obj->title_ = std::string(*utf8);
  if (obj->notification_) {
    notify_notification_set_summary(obj->notification_, obj->title_.c_str());
  }
}

void GtkNotify::GetTitle(Local property, const PropertyCallbackInfo& info) {
  GtkNotify* obj = ObjectWrap::Unwrap(info.Holder());
  info.GetReturnValue().Set(String::NewFromUtf8(info.GetIsolate(), obj->title_.c_str()).ToLocalChecked());
}

// SetIcon/GetIcon 同理...

void GtkNotify::Send(const FunctionCallbackInfo& args) {
  Isolate* isolate = args.GetIsolate();
  GtkNotify* obj = ObjectWrap::Unwrap(args.Holder());

  if (args.Length() < 1 || !args[0]->IsString()) {
    isolate->ThrowException(Exception::TypeError(
      String::NewFromUtf8(isolate, "send() requires a string message").ToLocalChecked()));
    return;
  }

  String::Utf8Value utf8(isolate, args[0]);
  std::string body(*utf8);

  // 延遲初始化 libnotify
  if (!obj->notification_) {
    notify_init("Node.js App");
    obj->notification_ = notify_notification_new(
      obj->title_.c_str(), body.c_str(), obj->icon_.c_str());
  } else {
    notify_notification_update(obj->notification_, obj->title_.c_str(), body.c_str(), obj->icon_.c_str());
  }

  GError* error = nullptr;
  gboolean success = notify_notification_show(obj->notification_, &error);
  if (!success) {
    isolate->ThrowException(Exception::Error(
      String::NewFromUtf8(isolate, error->message).ToLocalChecked()));
    g_error_free(error);
  }
  args.GetReturnValue().Set(Boolean::New(isolate, success));
}

5. 模組入口 (NODE_MODULE 宏)

NODE_MODULE(NODE_GYP_MODULE_NAME, GtkNotify::Init)

建構配置

現代 Node.js 使用 node-gyp + binding.gyp 取代舊版 wscript:

{
  "targets": [
    {
      "target_name": "gtknotify",
      "sources": [ "src/node_gtknotify.cpp" ],
      "include_dirs": [
        "

建構與測試

npm install node-gyp -g
node-gyp configure build
node demo/demo.js

關鍵遷移提示:從舊版 V8 API 到 N-API

  • Node.js 8+ 強烈建議使用 N-API (Node-API):穩定 ABI、跨版本二進位相容、無需重新編譯即可升級 Node 版本。
  • N-API 使用 napi_ 前綴函式,不直接操作 V8 Handle,改用 napi_value 不透明型別。
  • 現有 NAN (Native Abstractions for Node.js) 代碼可漸進式遷移至 N-API。

適用場景與替代方案

場景推薦方案
CPU 密集運算 (圖像處理、加密、壓縮)原生模組 / WebAssembly
系統級 API (檔案監控、硬體存取、桌面通知)原生模組
複用成熟 C/C++ 庫 (OpenCV、FFmpeg、LevelDB)原生模組 / FFI (node-ffi-napi)
單純效能優化先優化 JS 邏輯、Worker Threads、Cluster,再考慮原生

原生模組開發門檻較高 (需 C++、編譯工具鏈、Node 內部機制),但能突破 JS 單執行緒與沙箱限制。掌握此技能,讓你在關鍵路徑上獲得極致效能與系統整合能力。

copyright © 萬盛學電腦網 all rights reserved