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>
This commit is contained in:
Gabriel SchulhofandMichael Dawson authored and Danielle Adams committed 2021-02-16 09:12:56 -05:00
1 parent 42cc33cc48
commit 061939d2f6
6 files changed
+87 -7

No files matched your search

+6 -1
View File
@@ -1,9 +1,14 @@
'use strict';
const common = require('../../common');
const test_general = require(`./build/${common.buildType}/test_general`);
const filename = require.resolve(`./build/${common.buildType}/test_general`);
const test_general = require(filename);
const assert = require('assert');
// TODO(gabrielschulhof): This test may need updating if/when the filename
// becomes a full-fledged URL.
assert.strictEqual(test_general.filename, `file://${filename}`);
const [ major, minor, patch, release ] = test_general.testGetNodeVersion();
assert.strictEqual(process.version.split('-')[0],
`v${major}.${minor}.${patch}`);
+13
View File
@@ -1,3 +1,4 @@
#define NAPI_EXPERIMENTAL
#include <node_api.h>
#include <stdlib.h>
#include "../../js-native-api/common.h"
@@ -20,9 +21,21 @@ static napi_value testGetNodeVersion(napi_env env, napi_callback_info info) {
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(