安裝專案生成工具:
npm install -g node-gyp
mkdir node-addon-demo
cd node-addon-demo
mkdir src
{
"targets": [{
"target_name": "hello", // 輸出模組名:hello.node
"sources": [ "src/hello.cc" ], // C++ 源檔
"include_dirs": [ "
#include
#include
using namespace v8;
// 導出函數:Hello
Handle Hello(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("Hello world!"));
}
// 初始化:綁定到 exports
void Init(Handle
# 1. 生成 VS 專案檔
node-gyp configure
# 輸出:build/hello.vcxproj 等
# 2. 編譯(Release 模式)
node-gyp build --configuration=Release
# 輸出:build/Release/hello.node
或直接在 Visual Studio 開啟 `.sln` 進行編輯/除錯。
// test.js
var hello = require('./build/Release/hello');
console.log(hello.hello()); // 輸出: Hello world!
$ node test.js
Hello world!
| 問題 | 原因 | 解決 |
|---|---|---|
| LNK1104: cannot open 'node.lib' | VS 專案預期 Debug 目錄下有 node.lib | 在 ` |
| 模組名不匹配 | `NODE_MODULE(hello, Init)` 需與 `target_name`、檔名 `hello.node` 一致 | 三者保持一致:`target_name: "hello"`、`NODE_MODULE(hello, ...)`、`require('./hello')` |
| `conditions` 中 `-lnode.lib` 報錯 | 舊教材遺留配置,新版 `node-gyp` 自動鏈結 | 移除 `binding.gyp` 中 `libraries: ['-lnode.lib']` |
| Node 版本升級後模組失效 | ABI 變更,原生模組需重新編譯 | 使用 NAN (Native Abstractions for Node.js) 或 **Node-API (N-API)** 實現跨版本穩定 ABI |
N-API(Node 8+ 穩定)提供跨版本穩定 ABI,避免每次 Node 升級重編。配合 `node-addon-api` (C++ 包裝器) 體驗更佳:
// binding.gyp 追加
"dependencies": ["
// src/hello.cpp (node-addon-api 風格)
#include
Napi::String Hello(const Napi::CallbackInfo& info) {
return Napi::String::New(info.Env(), "Hello world!");
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("hello", Napi::Function::New(env, Hello));
return exports;
}
NODE_API_MODULE(hello, Init)
編譯後 `.node` 檔可在 Node 8~最新版直接載入,無需重編。