test(napi): access env variable in native

This commit is contained in:
LongYinan 2021-06-09 21:58:05 +08:00
parent 5b2037a6e4
commit 517fc35d90
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
2 changed files with 16 additions and 1 deletions

View file

@ -0,0 +1,7 @@
import test from 'ava'
const bindings = require('../index.node')
test('should be able to access env variable from native', (t) => {
t.is(bindings.getEnvVariable(), 'napi-rs')
})

View file

@ -1,4 +1,4 @@
use napi::{CallContext, JsBoolean, JsObject, JsUnknown, Result}; use napi::{CallContext, ContextlessResult, Env, JsBoolean, JsObject, JsString, JsUnknown, Result};
#[js_function(2)] #[js_function(2)]
pub fn instanceof(ctx: CallContext) -> Result<JsBoolean> { pub fn instanceof(ctx: CallContext) -> Result<JsBoolean> {
@ -32,11 +32,19 @@ pub fn cast_unknown(ctx: CallContext) -> Result<JsObject> {
Ok(unsafe { arg.cast::<JsObject>() }) Ok(unsafe { arg.cast::<JsObject>() })
} }
#[contextless_function]
fn get_env_variable(env: Env) -> ContextlessResult<JsString> {
env
.create_string_from_std(std::env::var("npm_package_name").unwrap())
.map(Some)
}
pub fn register_js(exports: &mut JsObject) -> Result<()> { pub fn register_js(exports: &mut JsObject) -> Result<()> {
exports.create_named_method("instanceof", instanceof)?; exports.create_named_method("instanceof", instanceof)?;
exports.create_named_method("isTypedarray", is_typedarray)?; exports.create_named_method("isTypedarray", is_typedarray)?;
exports.create_named_method("isDataview", is_dataview)?; exports.create_named_method("isDataview", is_dataview)?;
exports.create_named_method("strictEquals", strict_equals)?; exports.create_named_method("strictEquals", strict_equals)?;
exports.create_named_method("castUnknown", cast_unknown)?; exports.create_named_method("castUnknown", cast_unknown)?;
exports.create_named_method("getEnvVariable", get_env_variable)?;
Ok(()) Ok(())
} }