napi-rs/examples/napi/__tests__/worker.cjs
Caleb Everett 95dd6ef485
refactor(cli): refactor js-binding to support easier bundling. (#1957)
* Refactor js-binding to support bundling single-package artifacts

The existsSync check breaks the bundlers I've tested (esbuild, webpack,
ncc), so you cannot bundle napi-rs packages that have all binarys in a
single package.

I've tested this change with both single package and multi package
libraries.

* Update snapshots

* Update CI

* Fix electron test

---------

Co-authored-by: Caleb ツ Everett <calebev@amazon.com>
Co-authored-by: LongYinan <lynweklm@gmail.com>
2024-02-26 15:46:07 +08:00

53 lines
1.3 KiB
JavaScript

const { parentPort } = require('node:worker_threads')
const native = require('../index.cjs')
const isWasiTest = !!process.env.WASI_TEST
parentPort.on('message', ({ type }) => {
switch (type) {
case 'require':
parentPort.postMessage(
native.Animal.withKind(native.Kind.Cat).whoami() +
native.DEFAULT_COST,
)
break
case 'async:buffer':
Promise.all(
Array.from({ length: isWasiTest ? 2 : 100 }).map(() =>
native.bufferPassThrough(Buffer.from([1, 2, 3])),
),
)
.then(() => {
parentPort.postMessage('done')
})
.catch((e) => {
throw e
})
break
case 'async:arraybuffer':
Promise.all(
Array.from({ length: isWasiTest ? 2 : 100 }).map(() =>
native.arrayBufferPassThrough(Uint8Array.from([1, 2, 3])),
),
)
.then(() => {
parentPort.postMessage('done')
})
.catch((e) => {
throw e
})
break
case 'constructor':
let ellie
for (let i = 0; i < (isWasiTest ? 10 : 1000); i++) {
ellie = new native.Animal(native.Kind.Cat, 'Ellie')
}
parentPort.postMessage(ellie.name)
break
default:
throw new TypeError(`Unknown message type: ${type}`)
}
})