Skip to content

[Node-API] Symbol.toStringTag support #41358

Closed
@motla

Description

@motla

What is the problem this feature will solve?

Using Node-API, I would like my C/C++ addon to generate a JavaScript object decorated with a tag name, like this:

const obj = {
  name: "john",
  [Symbol.toStringTag]: "MyTag"
};

So I can get:
image

I believe this is not possible to set the Symbol.toStringTag property to an object created with the current Node-API.

What is the feature you are proposing to solve the problem?

I guess we need access to the global Symbol.toStringTag and other well-known Symbols defined in JavaScript.
Below is the Node.js example to create a new Symbol and set it as a property for an object (along other properties):

napi_value symbol_description;
napi_value name_symbol;
NODE_API_CALL(env,
napi_create_string_utf8(
env, "NameKeySymbol", NAPI_AUTO_LENGTH, &symbol_description));
NODE_API_CALL(env,
napi_create_symbol(env, symbol_description, &name_symbol));
napi_property_descriptor properties[] = {
{ "echo", 0, Echo, 0, 0, 0, napi_enumerable, 0 },
{ "readwriteValue", 0, 0, 0, 0, number, napi_enumerable | napi_writable, 0 },
{ "readonlyValue", 0, 0, 0, 0, number, napi_enumerable, 0},
{ "hiddenValue", 0, 0, 0, 0, number, napi_default, 0},
{ NULL, name_value, 0, 0, 0, number, napi_enumerable, 0},
{ NULL, name_symbol, 0, 0, 0, number, napi_enumerable, 0},
{ "readwriteAccessor1", 0, 0, GetValue, SetValue, 0, napi_default, 0},
{ "readwriteAccessor2", 0, 0, GetValue, SetValue, 0, napi_writable, 0},
{ "readonlyAccessor1", 0, 0, GetValue, NULL, 0, napi_default, 0},
{ "readonlyAccessor2", 0, 0, GetValue, NULL, 0, napi_writable, 0},
{ "hasNamedProperty", 0, HasNamedProperty, 0, 0, 0, napi_default, 0 },
};
NODE_API_CALL(env, napi_define_properties(
env, exports, sizeof(properties) / sizeof(*properties), properties));

Instead of creating a new Symbol we would have to use the existing Symbol.toStringTag.
Maybe you could consider to have a method like napi_get_symbol_tostringtag(env, &name_symbol) to replace napi_create_symbol(.. used on line 78.

What alternatives have you considered?

Explored the Node-API but I have no clue for a workaround in the C/C++ code.

For a root object returned by the add-on, one may use the add-on main.js file to add the property dynamically in JavaScript before the export, but it's not pretty.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues that request new features to be added to Node.js.node-apiIssues and PRs related to the Node-API.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions