我遇到了类似的问题,由于找不到足够的解决方案,我还为 javascript 创建了一个序列化库:https://github.com/wavesoft/jbb(事实上它有点多,因为它主要用于捆绑资源)
它与 Binary-JSON 很接近,但它增加了一些额外的功能,例如被编码对象的元数据和一些额外的优化,如重复数据删除、对其他包的交叉引用和结构级压缩。
但是有一个问题:为了使包大小保持较小,包中没有类型信息。此类信息在单独的“配置文件”中提供,描述您的编码和解码对象。出于优化原因,此信息以脚本的形式提供。
但您可以使用 gulp-jbb-profile (https://github.com/wavesoft/gulp-jbb-profile) 实用程序从简单的 YAML 对象规范生成编码/解码脚本,让您的生活更轻松,如下所示:
# The 'Person' object has the 'age' and 'isOld'
# properties
Person:
properties:
- age
- isOld
例如,您可以查看jbb-profile-three 个人资料。
准备好个人资料后,您可以像这样使用 JBB:
var JBBEncoder = require('jbb/encode');
var MyEncodeProfile = require('profile/profile-encode');
// Create a new bundle
var bundle = new JBBEncoder( 'path/to/bundle.jbb' );
// Add one or more profile(s) in order for JBB
// to understand your custom objects
bundle.addProfile(MyEncodeProfile);
// Encode your object(s) - They can be any valid
// javascript object, or objects described in
// the profiles you added previously.
var p1 = new Person(77);
bundle.encode( p1, 'person' );
var people = [
new Person(45),
new Person(77),
...
];
bundle.encode( people, 'people' );
// Close the bundle when you are done
bundle.close();
你可以这样读:
var JBBDecoder = require('jbb/decode');
var MyDecodeProfile = require('profile/profile-decode');
// Instantiate a new binary decoder
var binaryLoader = new JBBDecoder( 'path/to/bundle' );
// Add your decoding profile
binaryLoader.addProfile( MyDecodeProfile );
// Add one or more bundles to load
binaryLoader.add( 'bundle.jbb' );
// Load and callback when ready
binaryLoader.load(function( error, database ) {
// Your objects are in the database
// and ready to use!
var people = database['people'];
});