使用 Zig 開發 Nodejs 原生模塊
Node-API[1](前身爲 N-API)是 Nodejs 提供的用於構建原生插件的 API。它獨立於底層 JavaScript 運行時(例如 V8),並作爲 Node.js 自身的一部分進行維護。該 API 在不同版本的 Node.js 中具有穩定的應用二進制接口 (ABI)。其目的是使附加組件不受底層 JavaScript 引擎變化的影響,並允許爲一個主要版本編譯的模塊在以後的主要 Node.js 版本上運行,而無需重新編譯。
今天就來介紹如何用 Zig 開發一個 Nodejs 插件.
const std = @import("std");
const c = @cImport({
@cInclude("node_api.h");
});
export fn napi_register_module_v1(env: c.napi_env, exports: c.napi_value) c.napi_value {
var function: c.napi_value = undefined;
if (c.napi_create_function(env, null, 0, hello, null, &function) != c.napi_ok) {
_ = c.napi_throw_error(env, null, "Failed to create function");
return null;
}
if (c.napi_set_named_property(env, exports, "hello", function) != c.napi_ok) {
_ = c.napi_throw_error(env, null, "Failed to add function to exports");
return null;
}
return exports;
}
fn hello(env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value {
_ = info;
var result: c.napi_value = undefined;
const msg = "Hello from Zig!";
if (c.napi_create_string_utf8(env, msg.ptr, msg.len, &result) != c.napi_ok) {
_ = c.napi_throw_error(env, null, "Failed to create utf string");
return null;
}
return result;
}
使用如下命令來編譯:
ounter(line
zig build-lib -dynamic -lc -fallow-shlib-undefined -isystem $(brew --prefix node)/include/node hello.zig -femit-bin=zig-out/hello.node
-isystem
用來指定系統的 header 目錄,這裏設置爲 node 安裝目錄內的頭文件目錄。
之後用下面的腳本來測試:
const addon = require('./zig-out/hello.node');
console.log(addon.hello());
如果一切正常,你就可以看到 Hello from Zig!
的輸出!
加入我們
Zig 中文社區是一個開放的組織,我們致力於推廣 Zig 在中文羣體中的使用,有多種方式可以參與進來:
-
供稿,分享 [2] 自己使用 Zig 的心得
-
改進 ZigCC 組織下的開源項目 [3]
-
加入微信羣 [4]
參考資料
[1]
Node-API: https://nodejs.org/api/n-api.html
[2]
供稿,分享: https://ziglang.cc/contributing
[3]
開源項目: https://ask.ziglang.cc/github
[4]
微信羣: https://ask.ziglang.cc/weixin
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/08Xa64SryyucgTsim_f2mA