| 1 | # BSER Binary Serialization
|
|---|
| 2 |
|
|---|
| 3 | BSER is a binary serialization scheme that can be used as an alternative to JSON.
|
|---|
| 4 | BSER uses a framed encoding that makes it simpler to use to stream a sequence of
|
|---|
| 5 | encoded values.
|
|---|
| 6 |
|
|---|
| 7 | It is intended to be used for local-IPC only and strings are represented as binary
|
|---|
| 8 | with no specific encoding; this matches the convention employed by most operating
|
|---|
| 9 | system filename storage.
|
|---|
| 10 |
|
|---|
| 11 | For more details about the serialization scheme see
|
|---|
| 12 | [Watchman's docs](https://facebook.github.io/watchman/docs/bser.html).
|
|---|
| 13 |
|
|---|
| 14 | ## API
|
|---|
| 15 |
|
|---|
| 16 | ```js
|
|---|
| 17 | var bser = require('bser');
|
|---|
| 18 | ```
|
|---|
| 19 |
|
|---|
| 20 | ### bser.loadFromBuffer
|
|---|
| 21 |
|
|---|
| 22 | The is the synchronous decoder; given an input string or buffer,
|
|---|
| 23 | decodes a single value and returns it. Throws an error if the
|
|---|
| 24 | input is invalid.
|
|---|
| 25 |
|
|---|
| 26 | ```js
|
|---|
| 27 | var obj = bser.loadFromBuffer(buf);
|
|---|
| 28 | ```
|
|---|
| 29 |
|
|---|
| 30 | ### bser.dumpToBuffer
|
|---|
| 31 |
|
|---|
| 32 | Synchronously encodes a value as BSER.
|
|---|
| 33 |
|
|---|
| 34 | ```js
|
|---|
| 35 | var encoded = bser.dumpToBuffer(['hello']);
|
|---|
| 36 | console.log(bser.loadFromBuffer(encoded)); // ['hello']
|
|---|
| 37 | ```
|
|---|
| 38 |
|
|---|
| 39 | ### BunserBuf
|
|---|
| 40 |
|
|---|
| 41 | The asynchronous decoder API is implemented in the BunserBuf object.
|
|---|
| 42 | You may incrementally append data to this object and it will emit the
|
|---|
| 43 | decoded values via its `value` event.
|
|---|
| 44 |
|
|---|
| 45 | ```js
|
|---|
| 46 | var bunser = new bser.BunserBuf();
|
|---|
| 47 |
|
|---|
| 48 | bunser.on('value', function(obj) {
|
|---|
| 49 | console.log(obj);
|
|---|
| 50 | });
|
|---|
| 51 | ```
|
|---|
| 52 |
|
|---|
| 53 | Then in your socket `data` event:
|
|---|
| 54 |
|
|---|
| 55 | ```js
|
|---|
| 56 | bunser.append(buf);
|
|---|
| 57 | ```
|
|---|
| 58 |
|
|---|
| 59 | ## Example
|
|---|
| 60 |
|
|---|
| 61 | Read BSER from socket:
|
|---|
| 62 |
|
|---|
| 63 | ```js
|
|---|
| 64 | var bunser = new bser.BunserBuf();
|
|---|
| 65 |
|
|---|
| 66 | bunser.on('value', function(obj) {
|
|---|
| 67 | console.log('data from socket', obj);
|
|---|
| 68 | });
|
|---|
| 69 |
|
|---|
| 70 | var socket = net.connect('/socket');
|
|---|
| 71 |
|
|---|
| 72 | socket.on('data', function(buf) {
|
|---|
| 73 | bunser.append(buf);
|
|---|
| 74 | });
|
|---|
| 75 | ```
|
|---|
| 76 |
|
|---|
| 77 | Write BSER to socket:
|
|---|
| 78 |
|
|---|
| 79 | ```js
|
|---|
| 80 | socket.write(bser.dumpToBuffer(obj));
|
|---|
| 81 | ```
|
|---|