Giter VIP home page Giter VIP logo

napi_ext's Introduction

Napi Extensions

This crate extends napi-rs with:

  • Local futures runtime
  • [napi_async] macro for local futures
  • env.spawn_local_promise()
  • env.spawn_local()
  • JsPromise
  • JsRc

Run local futures with:

use napi::*;
use napi_ext::*;

#[napi_async]
async fn my_js_func(env: Env, num: JsNumber) -> napi::Result<JsString> {
  task::sleep(Duration::from_millis(1000)).await;
  
  // Log number in JavaScript context
  env.console_log(&[num])?;

  // Returns Promise<String>
  env.create_string("Hello World")
}

Local Thread Futures

Allows for the use of async channels, timers and other async utilities in Rust without blocking the main JavaScript thread while retaining the capability of interacting with the underlying JavaScript values.

Installation

Install the crate with:

cargo add napi_ext

Examples

Timers & Callbacks

use std::time::Duration;

use napi::*;
use napi_ext::*;

#[napi_derive::napi]
fn my_js_func(env: Env, callback: JsRc<JsFunction>) -> napi::Result<JsObject> {
  env.spawn_local(move |env| async move {
    task::sleep(Duration::from_millis(1000)).await;
    callback.inner(&env)?.call_without_args(None)?;
    Ok(())
  })
}
import napi from './napi.node'

napi.myJsFunc(() => console.log('Waited for 1 second'))

Channels and Threads

You may combine OS threads with async channels to coordinate off-thread workloads.

I recommend using async_std or async-channel for async utilities as the custom Futures reactor is not compatible with Tokio utilities.

use std::thread;
use std::time::Duration;
 
use napi::*;
use napi_ext::*;
use async_std::channel;
 
#[napi_derive::napi]
fn my_js_func(env: Env, callback: JsRc<JsFunction>) -> napi::Result<JsObject> {
  let (tx, rx) = channel::unbounded();
 
  thread::spawn(move || {
    for i in 0..10 {
      tx.send_blocking(i).unwrap();
      thread::sleep(Duration::from_millis(1000));
    }
  });
 
  env.spawn_local(move |env| async move {
    while let Ok(value) = rx.recv().await {
      println!("Got number: {}", value);
      callback.inner(&env)?.call(None, &[env.create_int32(value)?])?;
    }
 
    Ok(())
  })
}

Development

To setup the development environment ensure you have installed just, then run:

npm install
just run example-a

napi_ext's People

Contributors

alshdavid avatar

Stargazers

Richer avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.