Tokio
Real world example (opens in a new tab)
You can also run Tokio
futures in Node.js. With the tokio_rt
feature, napi-rs
will create a tokio runtime so that you can use Env::execute_tokio_future
to execute a future and return a JavaScript Promise
.
tokio_rt
needsThreadSafeFunction
under the hood, so enabletokio_rt
feature will enablenapi4
by default.
#[js_function(1)]
pub fn readfile(ctx: CallContext) -> Result<JsObject> {
let js_filepath = ctx.get::<JsString>(0)?;
let path_str = js_filepath.into_utf8()?.into_owned()?;
ctx.env.execute_tokio_future(
tokio::fs::read(path_str).map(|v| {
v.map_err(|e| {
Error::new(
Status::GenericFailure,
format!("failed to read file, {}", e),
)
})
}),
|&mut env, data| env.create_buffer_with_data(data).map(|v| v.into_raw()),
)
}
readfile('./test.txt').then((data) => {
console.log(data) // Buffer<00 03 ...>
})