hildjj / node-cbor

Encode and decode CBOR documents, with both easy mode, streaming mode, and SAX-style evented mode.
MIT License
357 stars 73 forks source link

Add option to omit undefined properties when encoding #134

Closed ninevra closed 3 years ago

ninevra commented 3 years ago

Currently, cbor.decode(cbor.encode({foo: undefined})) produces {foo: undefined}. This is wonderful if you're using CBOR as a way to serialize arbitrary javascript values. But, if your protocol treats {foo: undefined} identically to {} (which most javascript consumers probably do), then it means 5 bytes were unnecessarily spent encoding 'foo' and undefined.

This behavior can also make it harder to produce deterministic output. It's tedious to ensure that one's data never contains undefined-valued properties, and test suites often don't check this, making it easy to produce {foo: undefined} from one codepath and {} from another.

I suggest adding an encoding option omitUndefinedProperties, defaulting to false. When true, the encoder should skip encoding undefined-valued properties of plain objects. Maps can probably be left as-is, or have a separate toggle; I think it's a little harder to accidentally put undefined in a Map, and more likely for a protocol to care about the size of Maps.

(This issue follows up on the suggestion in https://github.com/hildjj/node-cbor/issues/83#issuecomment-412139114, per https://github.com/hildjj/node-cbor/issues/83#issuecomment-782953549.)

hildjj commented 3 years ago

Added in v7.0.2