zig-napi is a Zig package that provides a set of bindings to the Node-API (N-API) for Zig. It allows you to write native Node.js addons in Zig, enabling you to leverage Zig’s performance and safety features while interacting with Node.js.
This is how hello world
example looks like:
const std = @import("std");
const napi = @import("napi");
// Every napi module needs to call `registerModule` to register it with the N-API runtime.
comptime {
napi.registerModule(init);
}
fn hello(env: napi.Env, who: napi.Value) !napi.Value {
var buf: [64]u8 = undefined;
const len = try who.getValueString(.utf8, &buf);
const allocator = std.heap.page_allocator;
const message = try std.fmt.allocPrint(allocator, "Hello {s}", .{buf[0..len]});
defer allocator.free(message);
return try env.createString(.utf8, message);
}
pub fn init(env: napi.Env, exports: napi.Value) !napi.Value {
try exports.setNamedProperty(
"hello",
try env.createFunction(hello, null),
);
return exports;
}
const addon = require('../zig-out/lib/hello.node');
const assert = require('node:assert/strict');
assert.strictEqual('Hello Tom', addon.hello('Tom'));
assert.strictEqual('Hello Jack', addon.hello('Jack'));
Hope you find this package useful! If you have any questions or suggestions, feel free to open an issue or submit a pull request.