2011
Sep
23

这篇文章只适用於 Node.js version 0.10.x,如果你是使用 0.11 与 0.12 以上的版本,请忽略本文。

Node.js像php一样可以写extension,不过在Node.js里叫做addon,同样是使用C or C++,在php中我们是透过Zend function来制作 extension ,而在Node.js,是透过 Google v8 引擎来制作。

  • 第一步我们得先设定 python library的路径,我是设定成: PYTHONPATH=/usr/local/lib/python2.7
  • 第二步是写好你的c code
  • 第三步写一个wscript ,就如同makefile一样,指定要编译的档案名称
  • 第四步执行编译 sudo node-waf configure build ,执行后会自动建立build dir
  • 最后,写个 Node.js , require addon 来用吧

Node.js Addon 写法实作

现在我们就先写一个简单的 c code 来测试吧,首先我们要载入相关的header file,最基本的两个header是 v8 与 node ,include 后,顺便先呼叫 namespace,以方便后续使用

hello.cc
  1. #include "v8.h"
  2. #include "node.h"
  3. using namespace v8;
  4. using namespace node;

接著实做 init ,require Node.js addon 后,最先执行的function,这里我用v8 String物件,宣告一个字串hello,及一个字串world,并指定hello=world,再用两种不同的方式,定义function, 范例 「hello.cc 」

hello.cc
  1. extern "C" void init (Handle<Object> target){
  2. HandleScope scope;
  3. target->Set(String::New("hello"), String::New("world"));
  4. target->Set(String::New("func"),FunctionTemplate::New(func)->GetFunction());
  5. NODE_SET_METHOD(target, "func2", func2);
  6. }

实做 func与func2,这两个function,我这先简单写一点东西,测试一下罗

hello.cc
  1. static Handle<Value> func(const Arguments& args){
  2. return String::New("the return value");
  3. }
  4. static Handle<Value> func2(const Arguments& args){
  5. return True();
  6. }

编译 Node.js Addon

编译出来的 addon 副档名一定要是 .node ,否则执行会有问题。

make
  1. mode=compile g++ -Wall -O3 -fPIC -Dposix -DDSO_EXT=so -DREUSE_CONTEXT -shared -DHAVE_CONFIG_H -g -O2 -I/usr/local/include/node -c hello.cc -o hello.o
  2. g++ -shared -lpthread -lv8 -lrt -ldl -o hello.node hello.o

执行与测试 Node.js

写个js 载入 hello 并印出物件,范例「hello」

Example
  1. var s=require('./hello.node');
  2. console.log(s);
  3. console.log(s.func());
  4. console.log(s.func2())

结果输出:

Example
  1. [puritys]addon$ node hello.js
  2. { hello: 'world', func: [Function], func2: [Function] }
  3. the return value
  4. true

Node.js Addon 范例下载


目前回應 Comments(1 comments)

  • Sam 2014/03/14

    感謝版大分享, 可是為什麼compile出來要有.node?我看國外他們compile出來沒有加.node也可以, 這是版本問題嗎?

    Reply

    Admin

    每個檔案,習慣上都會給一個副檔名,所以我固定都會用 .node,如果副檔名是別的,例如 .so , .o 這樣 Node.js addon 會無法載入;若是你不給副檔名,也是可以正確載入的。

回應 (Leave a comment)