node-addon-api: Object spread not working with Napi::ObjectWrap

Objects implemented using Napi::ObjectWrap do not seem to support the object spread syntax.

The following code on an object implemented with Napi::ObjectWrap always creates an empty object. The two properties are implemented as instance accessors using Napi.

const addonSampleObject = new addon.SampleObject();
addonSampleObject.stringProp = "Hello World";
addonSampleObject.numberProp = 3.1415926536;

const spreadAddonSampleObject = {...addonSampleObject};

This code with an object implemented using Nan::ObjectWrap works as expected, creating an object with the two properties that have the same values as the original object.

To make it easy to reproduce I have created two GitHub repositories, one with a Napi implementation and one with a NAN implementation.

Am I doing something wrong? Is this a known limitation or maybe a bug?

Any advice is very much appreciated.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 18 (9 by maintainers)

Most upvoted comments

Hi @lili2012 ,

The original issue was only discussing how to enumerate the properties correctly for use with object spread. console.log internally uses util.inspect on objects to display them. If you want to use console.log() and show your object’s getters without using util.inspect, I can think of two ways:

  1. Assign a property [util.inspect.custom] to your object which will get called when using console.log and return the string you want to display to stdout. See documentation, StackOverflow example.

  2. Overwrite the console global with a new Console that changes the default inspect options or create a new console specifically for logging your objects.

globalThis.console = new Console({ stdout: process.stdout, stderr: process.stderr, inspectOptions: { getters: true } });
console.log(addonSampleObject);
/*
SampleObject {
  stringProp: [Getter/Setter: 'Hello World'],
  numberProp: [Getter/Setter: 3.1415926536]
}
*/