node/test/node-api/test_general/test_general.c
Gabriel Schulhof ad3ebed046 node-api: allow retrieval of add-on file name
Unlike JS-only modules, native add-ons are always associated with a
dynamic shared object from which they are loaded. Being able to
retrieve its absolute path is important to native-only add-ons, i.e.
add-ons that are not themselves being loaded from a JS-only module
located in the same package as the native add-on itself.

Currently, the file name is obtained at environment construction time
from the JS `module.filename`. Nevertheless, the presence of `module`
is not required, because the file name could also be passed in via a
private property added onto `exports` from the `process.dlopen`
binding.

As an attempt at future-proofing, the file name is provided as a URL,
i.e. prefixed with the `file://` protocol.

Fixes: https://github.com/nodejs/node-addon-api/issues/449
PR-URL: https://github.com/nodejs/node/pull/37195
Co-authored-by: Michael Dawson <mdawson@devrus.com>
Reviewed-By: Michael Dawson <midawson@redhat.com>
2021-02-09 23:34:30 -08:00

48 lines
1.7 KiB
C

#define NAPI_EXPERIMENTAL
#include <node_api.h>
#include <stdlib.h>
#include "../../js-native-api/common.h"
static napi_value testGetNodeVersion(napi_env env, napi_callback_info info) {
const napi_node_version* node_version;
napi_value result, major, minor, patch, release;
NODE_API_CALL(env, napi_get_node_version(env, &node_version));
NODE_API_CALL(env, napi_create_uint32(env, node_version->major, &major));
NODE_API_CALL(env, napi_create_uint32(env, node_version->minor, &minor));
NODE_API_CALL(env, napi_create_uint32(env, node_version->patch, &patch));
NODE_API_CALL(env,
napi_create_string_utf8(
env, node_version->release, NAPI_AUTO_LENGTH, &release));
NODE_API_CALL(env, napi_create_array_with_length(env, 4, &result));
NODE_API_CALL(env, napi_set_element(env, result, 0, major));
NODE_API_CALL(env, napi_set_element(env, result, 1, minor));
NODE_API_CALL(env, napi_set_element(env, result, 2, patch));
NODE_API_CALL(env, napi_set_element(env, result, 3, release));
return result;
}
static napi_value GetFilename(napi_env env, napi_callback_info info) {
const char* filename;
napi_value result;
NODE_API_CALL(env, node_api_get_module_file_name(env, &filename));
NODE_API_CALL(env,
napi_create_string_utf8(env, filename, NAPI_AUTO_LENGTH, &result));
return result;
}
static napi_value Init(napi_env env, napi_value exports) {
napi_property_descriptor descriptors[] = {
DECLARE_NODE_API_PROPERTY("testGetNodeVersion", testGetNodeVersion),
DECLARE_NODE_API_GETTER("filename", GetFilename),
};
NODE_API_CALL(env, napi_define_properties(
env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors));
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)