1.N-API(節點API)
Node-API 是一個穩定的 ABI(應用程式二進位介面),允許在升級 Node.js 版本時用 C/C++ 或 Rust 編寫本機插件,而無需重建。
| 方法 | 語言 | 建構工具 | 何時使用 |
|---|---|---|---|
| 節點插件 API | C++ | 節點 gyp | C/C++ 函式庫可用 |
| 納皮-RS | 鐵鏽 | 貨物.貨物 | Rust 項目,效能 |
| WASM | 任意 → WASM | wasm 包 | 便攜式、沙箱 |
| 工作執行緒 | JavaScript | 無 | CPU任務很簡單 |
2.napi-rs(Rust → Node.js)
# Tạo project napi-rs
npm create napi@latest
# Chọn: @myapp/native, supported platforms
// src/lib.rs
use napi_derive::napi;
use napi::Result;
#[napi]
pub fn fibonacci(n: u32) -> u64 {
match n {
0 => 0,
1 => 1,
_ => {
let (mut a, mut b) = (0u64, 1u64);
for _ in 2..=n {
let tmp = a + b;
a = b;
b = tmp;
}
b
}
}
}
#[napi]
pub fn hash_password(password: String, salt: String) -> Result {
use argon2::{self, Config};
let config = Config::default();
argon2::hash_encoded(password.as_bytes(), salt.as_bytes(), &config)
.map_err(|e| napi::Error::from_reason(e.to_string()))
}
// Sử dụng trong JS/TS
import { fibonacci, hashPassword } from '@myapp/native'
console.log(fibonacci(50)) // 12586269025 — nhanh hơn JS
const hash = hashPassword('mypassword', 'randomsalt')
3.有node-addon-api的C++插件
// addon.cc
#include <napi.h>
Napi::Value Add(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
double a = info[0].As<Napi::Number>().DoubleValue();
double b = info[1].As<Napi::Number>().DoubleValue();
return Napi::Number::New(env, a + b);
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("add", Napi::Function::New(env, Add));
return exports;
}
NODE_API_MODULE(addon, Init)
// binding.gyp
{
"targets": [{
"target_name": "addon",
"sources": ["addon.cc"],
"include_dirs": ["<!@(node -p \"require('node-addon-api').include\")"]
}]
}
4. 預先建置與分發
{
"scripts": {
"build": "napi build --release",
"prepublishOnly": "napi prepublish -t npm"
},
"napi": {
"name": "mylib",
"triples": {
"defaults": true,
"additional": ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu"]
}
}
}
5. 何時使用原生插件?
// Benchmark: Fibonacci(40)
// JavaScript: ~1200ms
// Rust (napi-rs): ~35ms (34x faster)
// WASM: ~50ms (24x faster)
// → Dùng native addons khi:
// 1. CPU-bound tasks (crypto, image processing, compression)
// 2. Cần tích hợp C/C++ libraries (FFmpeg, OpenCV)
// 3. Performance là critical
// 4. Cần memory-safe parallel processing (Rust)
下一篇: 測試 Node.js 應用程式 — 節點:測試、Vitest、Supertest。