Protobuf with NodeJS on Windows

2019-03-31 02:14发布

问题:

I would like to send simple TCP message to a device (Karotz) from NodeJS Script on Windows.

  • NodeJS correctly installed an working
  • TCP connection working
  • Here is my .proto file (http://wiki.karotz.com/index.php/Voos-message.proto)
  • I compile it to .desc using google's protoc

I don't know how to build my message to send it to the device ?

  • I read Google Description
  • And protobuff_for_node and other fork

But I don't understand how to install it on windows. Seems complicated because of native librarie.

Is there dead simple javascript librarie that read the .desc Schema and build the message ? Without native code or complicated stuff ?

回答1:

If you're using Node.js it's simpler to just use the NPM package version of the protobuf library it'll build it for you, assuming you have a C++ compiler on your machine:

> npm install protobuf

To build your message & parse and existing message:

var Schema    = require('protobuf').Schema;
var readFile  = require('fs').readFileSync;
var schema = new Schema(readFile(__dirname+'/Voos-message.desc'));
var VooMsg = schema['net.violet.voos.message.VoosMsg'];

// Convert to protobuf format
var msg = VooMsg.serialize({id:1, correlationId: 'hello'});

// Read it back
var outMsg = VooMag.parse(msg);

The protobuf library works very well and is easy to use. But if you want a pure JS version, have a look at: ProtoBufJS