This is a tiny module to help you convert between JSON data and ArrayBuffer, and you can use it in both Node.js and browsers.
npm install json-bufferify
In Node.js
// CommonJS
const bufferify = require('json-bufferify');
// ES6 Modules
import bufferify from 'json-bufferify';
In browsers
<script src="json-bufferify.js"></script>
In TypeScript
// Traditional style
import bufferify = require('json-bufferify');
// ES6 Modules
import bufferify from 'json-bufferify';
In Egret
Open “egretProperties.json” and Add the following code to “modules” node.
{
"name": "json-bufferify",
"path": "D:/Work/modules/json-bufferify"
}
let ws = new WebSocket(url);
ws.binaryType = 'arraybuffer';
ws.send(bufferify.encode(0, {
sex: 0,
name: 'Bob',
age: 25
}));
ws.on('message', data => {
console.log(bufferify.decode(0, {
name: 'string',
sex: 'number',
age: 'number'
}, data));
});
Convert JSON data to ArrayBuffer and return the DataView.
offset
- The start point of the DataView where to store the data.data
- The JSON data.Revert JSON data from ArrayBuffer and return it.
offset
- The start point of the DataView where to read the data.template
- The template of the JSON data.source
- The ArrayBuffer, or the Buffer in Node.js, or the DataView of the ArrayBuffer.let ws = new WebSocket(url);
ws.binaryType = 'arraybuffer';
ws.send(bufferify.encode(0, [1, 2, 3, 4, 5, 6, 7, 8, 9]));
ws.on('message', data => {
console.log(bufferify.decode(0, ['number'], data));
});
let ws = new WebSocket(url);
ws.binaryType = 'arraybuffer';
ws.send(bufferify.encode(0, {
obj: {
opcode: 8,
info: 'Hello'
},
arr: [1, 2, 3, 4, 5],
list: [{
name: 'Jerry',
id: '536598'
},
{
name: 'Tom',
id: '85947'
},
{
id: '459823',
name: 'Kevin'
}]
}));
ws.on('message', data => {
console.log(bufferify.decode(0, {
arr: ['number'],
obj: {
opcode: 'number',
info: 'string'
},
list: [{
id: 'string',
name: 'string'
}]
}, data));
});
This is licensed under the GNU LGPL, version 3 or later.