diff --git a/test_module/__test__/env.spec.ts b/test_module/__test__/env.spec.ts new file mode 100644 index 00000000..593bd823 --- /dev/null +++ b/test_module/__test__/env.spec.ts @@ -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') +}) diff --git a/test_module/src/env.rs b/test_module/src/env.rs index 43dda012..504a8b3f 100644 --- a/test_module/src/env.rs +++ b/test_module/src/env.rs @@ -1,4 +1,4 @@ -use napi::{CallContext, JsBoolean, JsObject, JsUnknown, Result}; +use napi::{CallContext, ContextlessResult, Env, JsBoolean, JsObject, JsString, JsUnknown, Result}; #[js_function(2)] pub fn instanceof(ctx: CallContext) -> Result { @@ -32,11 +32,19 @@ pub fn cast_unknown(ctx: CallContext) -> Result { Ok(unsafe { arg.cast::() }) } +#[contextless_function] +fn get_env_variable(env: Env) -> ContextlessResult { + env + .create_string_from_std(std::env::var("npm_package_name").unwrap()) + .map(Some) +} + pub fn register_js(exports: &mut JsObject) -> Result<()> { exports.create_named_method("instanceof", instanceof)?; exports.create_named_method("isTypedarray", is_typedarray)?; exports.create_named_method("isDataview", is_dataview)?; exports.create_named_method("strictEquals", strict_equals)?; exports.create_named_method("castUnknown", cast_unknown)?; + exports.create_named_method("getEnvVariable", get_env_variable)?; Ok(()) }