I'm decoding some messages and when the .proto-message-field is int64 type. the number becomes high {low} unsigned. So far so good. Knowing that the javascript does not have native support for int64, not intend to do any operation with this number in the Node.js But I need to save this number as it was originally, it can be string or numeric sequence. Can you tell me how I can change the Protobuf.js that, when decoding, int64 treat it as string? Is it Possible? Where Can I change this particularity?
Let's say you have a field named myMsg.myLongValue, then doing var str = ""+myMsg.myLongValue; should already do the trick as this calls toString() on the Long.js object.
More information on Long.js: https://github.com/dcodeIO/Long.js
Yhaaaaaa!!! Amazing!!! Amazing!! Im 2 months estuding about byte, buffer, protocol... and you resolved in 2 seconds! Sorry to use this channel to ask questions ... This would be a great improvement to the github ... A questions channel. dcodeIO .. thank you again.
To my needs, i fixed like this:
var fixInt64 = function(object) {
if(typeof object == "object") {
for(var propName in object) {
if(object.hasOwnProperty(propName)) {
if(typeof object[propName] == "object") {
if(object[propName].hasOwnProperty("high")){ // If is Long Object
object[propName] = Number(object[propName]);
}
}
}
}
}
return object;
}
The decoded message has 5 or 6 int64 fields,,, then a pass the decoded message by fixInt64(decodeMessage).. Is there a less-ugly way?
Actually, if you convert an int64 value to the number type and it is too large, it will lose information (JS has no true 64 bit number support on its own). The Long object also has a method for this: toNumber()
If you want to work with the long value safely, see the mathematical functions that Long.js provides.
A simple test for a Long object is: if (something instanceof ProtoBuf.Long) { ... }
Beautyfull!
Now it is:
var fixInt64 = function(obj) {
for(var key in obj) {
if(typeof obj[key] === 'object'){
fixInt64(obj[key]);
}
if(obj[key]instanceof ProtoBuf.Long){
obj[key] = obj[key].toNumber();
}
}
return obj;
}