DIV CSS 佈局教程網

在 Windows 7 上用 C++ 為 Node.js 撰寫原生擴充模組
編輯:JavaScript綜合知識     

Node.js 允許你用 C++ 撰寫原生 add-on,適合效能關鍵路徑或需要呼叫既有 C / C++ 函式庫的場景。本文記錄在 Windows 7 環境下從零建置一個 hello 模組的完整過程,以及過程中踩到的幾個坑。

前置環境

  • Node.js
  • Python 2.7(node-gyp 需要)
  • Visual Studio 2013

步驟一:安裝 node-gyp

npm install -g node-gyp

步驟二:建立工作目錄與 gyp 專案檔

建立 test 資料夾作為工作目錄,內部再建 src 存放 C++ 原始碼,並新增 binding.gyp:

{
  'targets': [
    {
      'target_name': 'hello',
      'sources': ['src/hello.cc']
    }
  ]
}

步驟三:撰寫 hello.cc

#include <node.h>
using namespace v8;

Handle<Value> Hello(const Arguments& args) {
  HandleScope scope;
  return scope.Close(String::New("Hello world!"));
}

void init(Handle<Object> target) {
  NODE_SET_METHOD(target, "hello", Hello);
}

NODE_MODULE(hello, init)

步驟四:設定與編譯

node-gyp configure
node-gyp build

configure 執行成功後會產生 build 目錄,裡頭就是 VS2013 的專案檔,你可以直接在 Visual Studio 裡編輯與偵錯;不想開 IDE 的話,用 node-gyp build 一行命令即可編譯。

步驟五:撰寫測試程式

var hello = require('./hello');
console.log(hello.hello());

踩坑記錄

1. 找不到 node.lib

在 C:\Users\<使用者>\.node-gyp\<版本>\ 這個目錄下,預設並沒有 Debug 子目錄。用 VS2013 編譯 Debug 版本時會出現:

error LNK1104: cannot open file
'C:\Users\Administrator\.node-gyp\0.10.33\Debug\node.lib'

解法很簡單:手動建立一個 Debug 目錄,再把對應你環境的 node.lib 複製進去即可。

2. 模組名稱必須與檔名一致

NODE_MODULE(hello, init) 中的 hello 是模組名稱,必須和輸出檔名保持一致。否則編譯階段不會報錯,執行 require('./hello.node') 時才會失敗——因為 require 不僅找檔案,也會去比對註冊的模組名稱。

3. 關於 'libraries' 設定

參考書籍時會看到 gyp 設定裡多一項:

'libraries': ['-lnode.lib']

加上這行之後,無論檔案路徑多正確,編譯都會持續抱怨找不到 node.lib;把檔案複製到工作目錄用命令列編譯可以通過,但在 VS2013 裡仍然失敗。對照官方範例後發現,現行版本並不需要這個參數,移除後一切正常。

補充提醒

本文使用的是 Handle、Arguments 這類 V8 舊版 API,在 Node.js 4 之後已被 N-API(Node-API)取代。新專案請優先採用 N-API,它與 Node 版本解耦,編譯出的二進位檔可以直接跨版本使用,不必每次升級 Node 就重新 build。

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