Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions call-js-from-async-worker-execute/node-addon-api/binding.gyp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"targets": [
{
"target_name": "dispatcher",
"sources": [ "src/binding.cc" ],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'include_dirs': ["<!@(node -p \"require('node-addon-api').include\")"],
'dependencies': ["<!(node -p \"require('node-addon-api').gyp\")"],
'conditions': [
['OS=="win"', {
"msvs_settings": {
"VCCLCompilerTool": {
"ExceptionHandling": 1
}
}
}],
['OS=="mac"', {
"xcode_settings": {
"CLANG_CXX_LIBRARY": "libc++",
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'MACOSX_DEPLOYMENT_TARGET': '10.7'
}
}]
]
}
]
}
25 changes: 25 additions & 0 deletions call-js-from-async-worker-execute/node-addon-api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict'

const { EventEmitter } = require('node:events');
const { dispatch } = require('bindings')('dispatcher');

class Socket extends EventEmitter {
constructor () {
super();
dispatch(this.emit.bind(this));
}
}

const socket = new Socket();

socket.on('open', () => {
console.log('opened');
});

socket.on('message', (message) => {
console.log(`message: ${message}`);
});

socket.on('close', () => {
console.log('closed');
});
15 changes: 15 additions & 0 deletions call-js-from-async-worker-execute/node-addon-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "call-js-from-async-worker-execute",
"version": "0.0.0",
"description": "Node.js Addons - calls JS from AsyncWorker::Execute",
"main": "index.js",
"private": true,
"gypfile": true,
"scripts": {
"start": "node index.js"
},
"dependencies": {
"node-addon-api": "*",
"bindings": "*"
}
}
101 changes: 101 additions & 0 deletions call-js-from-async-worker-execute/node-addon-api/src/binding.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#include <napi.h>

#include <chrono>
#include <thread>

class Dispatcher : public Napi::AsyncWorker {
public:
Dispatcher(Napi::Env env, Napi::Function& callback)
: Napi::AsyncWorker(env),
callback_(callback),
tsfn_{
Napi::ThreadSafeFunction::New(env, callback, "Dispatcher", 0, 1)} {}

virtual ~Dispatcher() override { tsfn_.Release(); }

void Execute() override {
// Since this method executes on a thread that is different from the main
// thread, we can't directly call into JavaScript. To trigger a call into
// JavaScript from this thread, ThreadSafeFunction needs to be used to
// communicate with the main thread, so that the main thread can invoke the
// JavaScript function.

napi_status status =
tsfn_.BlockingCall([](Napi::Env env, Napi::Function js_callback) {
js_callback.Call({Napi::String::New(env, "open")});
});
if (status != napi_ok) {
SetError("Napi::ThreadSafeNapi::Function.BlockingCall() failed");
return;
}

std::this_thread::sleep_for(std::chrono::seconds(1));
status = tsfn_.BlockingCall([](Napi::Env env, Napi::Function js_callback) {
js_callback.Call(
{Napi::String::New(env, "message"), Napi::String::New(env, "data1")});
});
if (status != napi_ok) {
SetError("Napi::ThreadSafeNapi::Function.BlockingCall() failed");
return;
}

std::this_thread::sleep_for(std::chrono::seconds(1));
status = tsfn_.BlockingCall([](Napi::Env env, Napi::Function js_callback) {
js_callback.Call(
{Napi::String::New(env, "message"), Napi::String::New(env, "data2")});
});
if (status != napi_ok) {
SetError("Napi::ThreadSafeNapi::Function.BlockingCall() failed");
return;
}

std::this_thread::sleep_for(std::chrono::seconds(1));
status = tsfn_.BlockingCall([](Napi::Env env, Napi::Function js_callback) {
js_callback.Call(
{Napi::String::New(env, "message"), Napi::String::New(env, "data3")});
});
if (status != napi_ok) {
SetError("Napi::ThreadSafeNapi::Function.BlockingCall() failed");
return;
}

status = tsfn_.BlockingCall([](Napi::Env env, Napi::Function js_callback) {
js_callback.Call({Napi::String::New(env, "close")});
});
if (status != napi_ok) {
SetError("Napi::ThreadSafeNapi::Function.BlockingCall() failed");
return;
}
}

void OnError(Napi::Error const& error) override {
callback_.Call({Napi::String::New(Env(), "error"), error.Value()});
}

private:
Napi::Function callback_;
Napi::ThreadSafeFunction tsfn_;
};

void Dispatch(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();

if (info.Length() < 1 || !info[0].IsFunction()) {
Napi::TypeError::New(
env, "The first argument needs to be the callback function.")
.ThrowAsJavaScriptException();
return;
}

Napi::Function callback = info[0].As<Napi::Function>();

Dispatcher* dispatcher = new Dispatcher(env, callback);
dispatcher->Queue();
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("dispatch", Napi::Function::New(env, Dispatch));
return exports;
}

NODE_API_MODULE(dispatcher, Init)