Skip to main content

N-API Native Addon

For CPU-intensive tasks or when implementing workers in languages such as C++ or Rust, you can leverage Piscina's support for native addons as worker implementations.

Setup

First, get the example from the Piscina GitHub repository.

Then install the dependencies:

npm i

Build the native addon artifacts:

npm run prebuild

The prebuild command will build the binary artifacts for the native addon and will put them in the prebuilds folder. Because of how prebuilds work, we need to use an intermediate JavaScript file to load and export them. For this example native addon, you'll find that in the examples folder.

The index.js illustrates how to load and use the native addon as the worker implementation:

index.js
const Piscina = require('piscina');
const { resolve } = require('path');

const pool = new Piscina({
filename: resolve(__dirname, 'example')
});

(async () => {
// Submit 5 concurrent tasks
console.log(await Promise.all([
pool.run(),
pool.run(),
pool.run(),
pool.run(),
pool.run()
]));
})();

You can also check out this example on github.