napi-rs/test_module/__test__/napi4/uv.spec.js
Ouyang Yadong 00454eb577 refactor(napi): use get_uv_event_loop instead of uv_default_loop
Using the uv_loop_s from napi_env is safer as it's possible that
there are multiple Workers, and therefore multiple uv_loop_s.
2020-08-18 13:55:35 +08:00

44 lines
1.1 KiB
JavaScript

const test = require('ava')
const { join, resolve } = require('path')
const { readFileSync } = require('fs')
const bindings = require('../../index.node')
const napiVersion = require('../napi-version')
let threadMod
try {
threadMod = require('worker_threads')
} catch (err) {
//
}
const filepath = join(__dirname, './example.txt')
test('should execute future on libuv thread pool', async (t) => {
if (napiVersion < 4) {
t.is(bindings.uvReadFile, undefined)
return
}
const fileContent = await bindings.uvReadFile(filepath)
t.true(Buffer.isBuffer(fileContent))
t.deepEqual(readFileSync(filepath), fileContent)
})
test('should execute future on libuv thread pool of "Worker"', async (t) => {
// Test in threads if current Node.js supports "worker_threads".`
if (!threadMod || napiVersion < 4) {
return
}
const { Worker } = threadMod
const script = resolve(__dirname, './uv_worker.js')
const worker = new Worker(script)
const success = await new Promise((resolve) => {
worker.on('message', (success) => {
resolve(success)
})
})
t.is(success, true)
})