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)
// 載入編譯產出的原生模組
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('通知內容訊息');
#include
#include
#include
#include
#include
using namespace v8;
using namespace node;
class GtkNotify : public ObjectWrap {
public:
static void Init(Local
Persistent GtkNotify::constructor;
void GtkNotify::Init(Local
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));
}
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
napi_ 前綴函式,不直接操作 V8 Handle,改用 napi_value 不透明型別。| 場景 | 推薦方案 |
|---|---|
| CPU 密集運算 (圖像處理、加密、壓縮) | 原生模組 / WebAssembly |
| 系統級 API (檔案監控、硬體存取、桌面通知) | 原生模組 |
| 複用成熟 C/C++ 庫 (OpenCV、FFmpeg、LevelDB) | 原生模組 / FFI (node-ffi-napi) |
| 單純效能優化 | 先優化 JS 邏輯、Worker Threads、Cluster,再考慮原生 |
原生模組開發門檻較高 (需 C++、編譯工具鏈、Node 內部機制),但能突破 JS 單執行緒與沙箱限制。掌握此技能,讓你在關鍵路徑上獲得極致效能與系統整合能力。