jackdbd / zig-nodeapi-example

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Zig Node-API example

Node-API - 9 CI Linux CI MacOS CI Windows

Minimal repo to show how to create a Node.js native addon using Zig and the Node-API.

Instructions

Use zigup to download and fetch the latest Zig compiler:

zigup fetch master
zigup default master

Double check your Zig version:

zig version

Have a look at the Node-API version matrix and decide which version of the Node-API you want to target, and what is the minimum Node.js version that uses that version of the Node-API. For example, Node-API version 9 is supported in Node.js v18.17.0+, 20.3.0+, 21.0.0 and all later versions.

⚠️ Node-API versions are additive and versioned independently from Node.js.

For example, let's say you want to target Node-API version 9. The minimum Node.js version that supports Node-API version 9 is 18.17.0. So, be sure to use Node.js when building and testing this native addon.

nvm install 18.17.0
nvm use 18.17.0

Double check your Node.js version:

node -v

Compile for Linux

Download the Node-API headers:

./download-node-headers.sh
# or zig build download-node-headers

Build the native addon using zig build-lib (both in Debug mode and in ReleaseFast mode):

npm run build

In alternative, you can build the native addon using build.zig:

zig build
mkdir -p dist/debug && mv zig-out/lib/libaddon.so dist/debug/addon.node

zig build -Doptimize=ReleaseFast
mkdir -p dist/release && mv zig-out/lib/libaddon.so dist/release/addon.node

Run all tests:

npm test

Try a few examples:

npm run example:bare-minimum
npm run example:greet

Compile for Windows

Download the Node-API headers (if you haven't already) and both node.exe and node.lib:

./download-node-headers.sh
./download-node-exe-and-lib.sh

Compile for Windows x86_64:

zig build --build-file build-windows-x86-64.zig

Try a few examples:

NODE_SKIP_PLATFORM_CHECK=1 wine deps/node-v18.17.0/win-x64/node.exe examples/bare-minimum-win.cjs

NODE_SKIP_PLATFORM_CHECK=1 wine deps/node-v18.17.0/win-x64/node.exe examples/greet-win.cjs

⚠️ You need to set NODE_SKIP_PLATFORM_CHECK=1 otherwise a Node.js check immediately stops the script execution.

Credits

About


Languages

Language:Zig 62.7%Language:Shell 21.8%Language:JavaScript 15.5%