sitegui / js-binary

Encode/decode to a custom binary format, much more compact and faster than JSON/BSON
MIT License
91 stars 23 forks source link

Doesn't support buffers. #5

Closed jdalton closed 6 years ago

jdalton commented 6 years ago

The types file is missing an buffer (lower case) type so there is no write method to call for them and encode errors out.

If the schema has a buffer it will be of a type buffer (lower case) but the type for lookup is Buffer capitalized so it will miss finding the correct writer.

Lower casing the Buffer references here: https://github.com/sitegui/js-binary/blob/master/lib/Type.js#L71

and: https://github.com/sitegui/js-binary/blob/master/lib/types.js#L131-L142

resolves the issue.

sitegui commented 6 years ago

Hello @jdalton ,

Sorry, I couldn't understand what you're referring to. Can you provide some concrete example?

The 'Buffer' type can be used directly with new Type('Buffer'), like this:

let Type = require('js-binary').Type,
  buffer = Buffer.from('hello'),
  type = new Type('Buffer'),
  encoded = type.encode(buffer),
  decoded = type.decode(encoded)
console.log(buffer, decoded) // <Buffer 68 65 6c 6c 6f> <Buffer 68 65 6c 6c 6f>
jdalton commented 6 years ago

If your JSON object contains a property that is a buffer it will run into the issue above because the buffer is typeof a "buffer" and not Buffer (capital B).

sitegui commented 6 years ago

There is most likely some misunderstanding from my part over this issue.

The following code encodes an object with a buffer as a property:

let Type = require('js-binary').Type,
  schema = new Type({prop: 'Buffer'}),
  value = {prop: Buffer.from('hello')},
  encoded = schema.encode(value),
  decoded = schema.decode(encoded)
console.log(value, decoded) // { prop: <Buffer 68 65 6c 6c 6f> } { prop: <Buffer 68 65 6c 6c 6f> }

If you meant encoding a Buffer instance as json, this works, but not how one'd expect, since typeof Buffer.from('hello') === 'object':

let type = new Type({prop: 'json'})
type.decode(type.encode({prop: Buffer.from('hello')}))
// { prop: { type: 'Buffer', data: [ 104, 101, 108, 108, 111 ] } }

I don't see the issue here...

jdalton commented 6 years ago

Hmm interesting. I'm no longer seeing the issue. I had been able to reproduce a typeof "buffer".