All Projects → mika-fischer → napi-thread-safe-callback

mika-fischer / napi-thread-safe-callback

Licence: other
C++ utility class to perform callbacks into JavaScript from any thread

Programming Languages

C++
36643 projects - #6 most used programming language
javascript
184084 projects - #8 most used programming language
python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to napi-thread-safe-callback

node-screenlogic
Pentair ScreenLogic Javascript library using Node.JS
Stars: ✭ 38 (-38.71%)
Mutual labels:  node-js, nodejs-modules
vayder
Easy and concise validations for Express routes
Stars: ✭ 26 (-58.06%)
Mutual labels:  node-js, nodejs-modules
arcscord
A Discord library written in typescript
Stars: ✭ 18 (-70.97%)
Mutual labels:  node-js, nodejs-modules
win-ca
Get Windows System Root certificates
Stars: ✭ 78 (+25.81%)
Mutual labels:  node-js, napi
node-healthchecks-api
The Node.js implementation of the Health Checks API by Hootsuite
Stars: ✭ 25 (-59.68%)
Mutual labels:  node-js
Mastering-Node.js
📚 Belajar Dengan Jenius Node.js bareng Gun Gun Febrianza
Stars: ✭ 57 (-8.06%)
Mutual labels:  node-js
redive linebot
基於 Bottender 框架實作出的,公主連結聊天機器人,附加其他實用管理功能。
Stars: ✭ 20 (-67.74%)
Mutual labels:  node-js
nodejsdesignpatterns.com
Source for Website for Node.js Design Patterns, book by Mario Casciaro and Luciano Mammino, published by Packt (https://nodejsdp.link/buy)
Stars: ✭ 27 (-56.45%)
Mutual labels:  node-js
discord-clock
A simple clock script for your bot to show what time it is in your server | Discord.js v13 ready!
Stars: ✭ 29 (-53.23%)
Mutual labels:  node-js
async-container
Scalable multi-thread multi-process containers for Ruby.
Stars: ✭ 58 (-6.45%)
Mutual labels:  threads
proffy
React Native + ReactJS + NodeJS project developed on RocketSeat NexLevelWeek. This project is based on an application for connect students and teachers.
Stars: ✭ 30 (-51.61%)
Mutual labels:  node-js
proffy
📗 Sua plataforma de estudos online.
Stars: ✭ 24 (-61.29%)
Mutual labels:  node-js
Density-Wars
Real time peer to peer RTS game running on WebGL (WIP).
Stars: ✭ 60 (-3.23%)
Mutual labels:  node-js
js-threaddb
This project has been moved to https://github.com/textileio/js-textile
Stars: ✭ 13 (-79.03%)
Mutual labels:  threads
karachi
Repository for organizing the karachi nodeschools events
Stars: ✭ 21 (-66.13%)
Mutual labels:  node-js
jenni
👩‍💻 Jenkins Personal Assistant - CLI to interact with Jenkins server
Stars: ✭ 40 (-35.48%)
Mutual labels:  node-js
mutode
Mutation testing for JavaScript and Node.js
Stars: ✭ 61 (-1.61%)
Mutual labels:  node-js
barnowl
Technology-agnostic middleware for RFID, RTLS and M2M, enabling location-aware physical spaces. We believe in an open Internet of Things.
Stars: ✭ 25 (-59.68%)
Mutual labels:  node-js
minimal-node-application
Basic Node Babel Server
Stars: ✭ 126 (+103.23%)
Mutual labels:  node-js
IT API
The Internet services of the IT department of Alexander Technological Education Institute of Thessaloniki
Stars: ✭ 14 (-77.42%)
Mutual labels:  node-js

Napi Thread-Safe Callback

npm Build Status Build status dependencies Status devDependencies Status

This package contains a header-only C++ helper class to facilitate calling back into JavaScript from threads other than the Node.JS main thread.

Examples

Perform async work in new thread and call back with result/error

void example_async_work(const CallbackInfo& info)
{
    // Capture callback in main thread
    auto callback = std::make_shared<ThreadSafeCallback>(info[0].As<Function>());
    bool fail = info.Length() > 1;

    // Pass callback to other thread
    std::thread([callback, fail]
    {
        try
        {
            // Do some work to get a result
            if (fail)
                throw std::runtime_error("Failure during async work");
            std::string result = "foo";

            // Call back with result
            callback->call([result](Napi::Env env, std::vector<napi_value>& args)
            {
                // This will run in main thread and needs to construct the
                // arguments for the call
                args = { env.Undefined(), Napi::String::New(env, result) };
            });
        }
        catch (std::exception& e)
        {
            // Call back with error
            callback->callError(e.what());
        }
    }).detach();
}

Perform async work in new thread, call back with result/error and check return value

void example_async_return_value(const CallbackInfo& info)
{
    auto callback = std::make_shared<ThreadSafeCallback>(info[0].As<Function>());
    std::thread([callback]
    {
        try
        {
            int result = 0;
            while (true)
            {
                // Do some work...
                try
                {
                    result += 1;
                    if (result > 20)
                        throw std::runtime_error("Failure during async work");
                }
                catch (std::exception &e)
                {
                    // Call back with error
                    // Note that this will cause the thread to exit and the
                    // ThreadSafeCallback to be destroyed. But the callback
                    // will still be called, even afterwards
                    callback->callError(e.what());
                    throw;
                }
                // Call back into Javascript with current result
                auto future = callback->call<bool>(
                    [result](Env env, std::vector<napi_value> &args) {
                        args = {env.Undefined(), Number::New(env, result)};
                    },
                    [](const Value &val) {
                        return val.As<Boolean>().Value();
                    });
                // This blocks until the JS call has returned a value
                // In case the callback throws we just let the exception
                // bubble up and end the thread
                auto continue_running = future.get();
                if (!continue_running)
                    break;
            }
        }
        catch (...) 
        {
            // Ignore errors
        }
    }).detach();
}

Usage

  1. Add a dependency on this package to package.json:
  "dependencies": {
    "napi-thread-safe-callback": "0.0.1",
  }
  1. Reference this package's include directory in binding.gyp:
  'include_dirs': ["<!@(node -p \"require('napi-thread-safe-callback').include\")"],
  1. Include the header in your code:
#include "napi-thread-safe-callback.hpp"

Exception handling

Exceptions need to be enabled in the native module. To do this use the following in binding.gyp:

  'cflags!': [ '-fno-exceptions' ],
  'cflags_cc!': [ '-fno-exceptions' ],
  'xcode_settings': {
    'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
    'CLANG_CXX_LIBRARY': 'libc++',
    'MACOSX_DEPLOYMENT_TARGET': '10.7',
  },
  'msvs_settings': {
    'VCCLCompilerTool': { 'ExceptionHandling': 1 },
  },
  'conditions': [
    ['OS=="win"', { 'defines': [ '_HAS_EXCEPTIONS=1' ] }]
  ]
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].