2016-02-17 51 views
1

我是新來的谷歌平緩衝區。如何將一個JavaScript數組序列化爲Google flat buffers?

我想串行化對象的數組,以便使用nodeJS在網絡上傳輸它。

首先我創建了一個FBS文件,並與flatc編譯:

namespace MyAlcoholist; 

table Drink { 
drink_type_name: string; 
drink_company_name: string; 
drink_brand_name: string; 
drink_flavor_type_name : string; 
liquid_color_type_name : string; 
liquid_color_is_transparent : bool; 
alcohol_vol : float; 
calories_for_100g : uint; 
global_image_id: ulong; 
drink_flavor_id: ulong; 
} 

root_type Drink; 

編譯器生成一個名爲drink_generated.js文件。

然後我在Nodejs中創建了以下實用程序模塊。

var flatbuffers = require('../js/flatbuffers').flatbuffers; 
var builder = new flatbuffers.Builder(1); 

var drink = require('../fbs/drink_generated').MyAlcoholist; // Generated by `flatc`. 

function drinkArrayToIdl(drinkArray) { 
drinkArray.forEach(function (element, index, array) { 
    var drinkObj = element; 
    drink.Drink.startDrink(builder); 
    var drinkBrandName = builder.createString(drinkObj.drink_brand_name); 
    var drinkCompanyName = builder.createString(drinkObj.drink_company_name); 
    var drinkflavorTypeName = builder.createString(drinkObj.drink_flavor_type_name); 
    var drinkTypeName = builder.createString(drinkObj.drink_type_name); 
    var liquidColorTypeName = builder.createString(drinkObj.liquid_color_type_name); 
    drink.Drink.addAlcoholVol(builder, drinkObj.alcohol_vol); 
    drink.Drink.addCaloriesFor100g(builder,drinkObj.calories_for_100g); 
    drink.Drink.addDrinkBrandName(builder,drinkBrandName); 
    drink.Drink.addDrinkCompanyName(builder,drinkCompanyName); 
    drink.Drink.addDrinkFlavorId(builder,drinkObj.drink_flavor_id); 
    drink.Drink.addDrinkFlavorTypeName(builder, drinkflavorTypeName); 
    drink.Drink.addDrinkTypeName(builder,drinkTypeName); 
    drink.Drink.addGlobalImageId(builder,drinkObj.global_image_id); 
    drink.Drink.addLiquidColorIsTransparent(builder,drinkObj.is_transparent); 
    drink.Drink.addLiquidColorTypeName(builder,liquidColorTypeName); 
    drink.Drink.endDrink(builder); 
}) 
} 

module.exports.drinkArrayToIdl=drinkArrayToIdl; 

現在基於https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html我需要與builder.finish(var)關閉緩衝區,然後用builder.dataBuffer()獲取緩衝區。

我有理解我需要什麼樣的VAR提供給builder.finish(var)

我知道一個問題,endDrink()返回,我可以打電話,收緩衝區中的變量,但它只是一個飲料的功能。我想能夠插入許多對象到該緩衝區。

是可能的嗎?我做對了嗎?

有關該問題的任何信息將不勝感激。

回答

0

添加一個table Drinks { drinks:[Drink]; }並使之成爲新的root_type。然後在向量中收集所有返回值endDrink,並使用它創建一個Drinks表。

另外,由於對象不應嵌套,因此請在startDrink之前將所有呼叫移至createString

相關問題