DIV CSS 佈局教程網

用 Node.js 為其他程式撰寫原生擴充模組
編輯:JavaScript綜合知識     

Node.js 的擴充機制讓 JavaScript 能與 C++ 應用直接互動。本文以一個名為 node-notify 的 GTK+ 通知模組為例,走過從專案結構、C++ 類別撰寫、編譯到打包成 npm 模組的完整流程。

專案結構

.
|-- build/                    # 擴充編譯後的產物
|-- demo/
|   `-- demo.js               # 用來測試擴充的 Node 腳本
|-- src/
|   `-- node_gtknotify.cpp    # C++ 與 JavaScript 的對映層
`-- wscript                   # node-waf 的建置設定

先定義 API

動手寫 C++ 之前,先把使用端長什麼樣子定下來:

// 載入擴充,notify 上只會有一個建構函數 notification()
var notify = require("../build/default/gtknotify.node");

var notification = new notify.notification();
notification.title = "Notification title";
notification.icon  = "emblem-default";
notification.send("Notification message");

繼承 node::ObjectWrap

要建立 Node 擴充,需要寫一個繼承 node::ObjectWrap 的 C++ 類別,它提供了與 JavaScript 互動所需的公共方法。基本框架如下:

#include <v8.h>
#include <node.h>
#include <string>
#include <gtkmm.h>
#include <libnotifymm.h>

using namespace v8;

class Gtknotify : node::ObjectWrap {
private:
public:
  Gtknotify() {}
  ~Gtknotify() {}

  static void Init(Handle target) {
    // Node 透過 require() 載入擴充時會呼叫這裡
  }
};

v8::Persistent<FunctionTemplate> Gtknotify::persistent_function_template;

extern "C" {   // C++ 的名稱修飾問題,這裡用 extern "C"
  static void init(Handle target) {
    Gtknotify::Init(target);
  }
  NODE_MODULE(gtknotify, init);
}

Init 方法的三件事

一、宣告建構函數並綁定到目標變數,讓 require("notification") 之後可以用 n.notification():

v8::Local<FunctionTemplate> local_function_template = v8::FunctionTemplate::New(New);
Gtknotify::persistent_function_template = v8::Persistent<FunctionTemplate>::New(local_function_template);
Gtknotify::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1);
Gtknotify::persistent_function_template->SetClassName(v8::String::NewSymbol("Notification"));
target->Set(String::NewSymbol("notification"),
            Gtknotify::persistent_function_template->GetFunction());

二、宣告屬性 n.title 與 n.icon,分別對應 getter 與 setter:

Gtknotify::persistent_function_template->InstanceTemplate()
  ->SetAccessor(String::New("title"), GetTitle, SetTitle);
Gtknotify::persistent_function_template->InstanceTemplate()
  ->SetAccessor(String::New("icon"), GetIcon, SetIcon);

三、宣告原型方法 n.send():

NODE_SET_PROTOTYPE_METHOD(Gtknotify::persistent_function_template, "send", Send);

實作各個方法

建構式 New():建立類別的新實例、設定初始值,並把 C++ 物件包成 JavaScript 物件後回傳。

std::string title;
std::string icon;

static Handle<Value> New(const Arguments& args) {
  HandleScope scope;
  Gtknotify* gtknotify_instance = new Gtknotify();
  gtknotify_instance->title = "Node.js";
  gtknotify_instance->icon  = "terminal";
  gtknotify_instance->Wrap(args.This());
  return args.This();
}

getter 與 setter:本質上就是 C++ 與 V8 之間的值轉換。

static v8::Handle<Value> GetTitle(v8::Local<v8::String> property,
                                  const v8::AccessorInfo& info) {
  Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
  return v8::String::New(gtknotify_instance->title.c_str());
}

static void SetTitle(Local<String> property, Local<Value> value,
                     const AccessorInfo& info) {
  Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(info.Holder());
  v8::String::Utf8Value v8str(value);
  gtknotify_instance->title = *v8str;
}
// GetIcon / SetIcon 寫法相同

原型方法 Send():取出 this 上的 C++ 物件,用它的屬性組出通知並顯示。

static v8::Handle<Value> Send(const Arguments& args) {
  v8::HandleScope scope;
  Gtknotify* gtknotify_instance = node::ObjectWrap::Unwrap<Gtknotify>(args.This());
  v8::String::Utf8Value v8str(args[0]);

  Notify::init("Basic");
  Notify::Notification n(gtknotify_instance->title.c_str(), *v8str,
                         gtknotify_instance->icon.c_str());
  n.show();
  return v8::Boolean::New(true);
}

編譯

node-waf 是編譯 Node 擴充的建置工具,流程透過 wscript 設定:

def set_options(opt):
  opt.tool_options("compiler_cxx")

def configure(conf):
  conf.check_tool("compiler_cxx")
  conf.check_tool("node_addon")
  conf.check_cfg(package='gtkmm-2.4', args='--cflags --libs', uselib_store='LIBGTKMM')
  conf.check_cfg(package='libnotifymm-1.0', args='--cflags --libs', uselib_store='LIBNOTIFYMM')

def build(bld):
  obj = bld.new_task_gen("cxx", "shlib", "node_addon")
  obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall"]
  obj.target = "gtknotify"
  obj.source = "src/node_gtknotify.cpp"
  obj.uselib = ['LIBGTKMM', 'LIBNOTIFYMM']

在專案根目錄執行 node-waf configure && node-waf build,順利的話產物會落在 ./build/default/gtknotify.node,可以直接在互動環境測試:

$ node
> var notif = require('./build/default/gtknotify.node');
> n = new notif.notification();
{ icon: 'terminal', title: 'Node.js' }
> n.send("Hello World!");
true

打包成 npm 模組

要與社群分享成果,npm 是最合適的管道。在根目錄建立 package.json:

{
  "name" : "notify",
  "version" : "v0.1.0",
  "scripts" : {
    "preinstall" : "node-waf configure && node-waf build",
    "preuninstall" : "rm -rf build/*"
  },
  "main" : "build/default/gtknotify.node",
  "description" : "Description of the extension....",
  "homepage" : "https://github.com/olalonde/node-notify",
  "author" : {
    "name" : "Olivier Lalonde",
    "email" : "olalonde@gmail.com",
    "url" : "https://www.syskall.com/"
  },
  "repository" : {
    "type" : "git",
    "url" : "https://github.com/olalonde/node-notify.git"
  }
}

欄位名稱不可含 node 或 js 這類隱含關鍵字;scripts 讓安裝與移除時自動編譯與清理。更多格式細節可用 npm help json 查閱,多數欄位其實都是選填的。

本地測試時,npm install 即可安裝;npm link 則會建立一個指向開發目錄的連結,改完程式不必反覆安裝移除。準備好後先 npm adduser 註冊帳號,再於根目錄執行 npm publish,其他人就能用 npm install 你的包名 安裝了。

要注意的是,本文示範的 node-waf 與這套 V8 API 屬於 Node 早期(0.2~0.4 世代)的寫法,後續已被 node-gyp 與 NAN、Node-API 取代。理解這套流程有助於看懂老專案,但新專案請改用 node-gyp 或 Node-API。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved