Home > Software engineering >  protobuf.js using CommonJS?
protobuf.js using CommonJS?

Time:07-31

I am relatively new to JS but very familiar with protobuf. I'm currently designing a web page hosted from a Java HTTP server, and would like to implement protobuf communication between them.

My issue is on the browser side. After some research I found the protobuf.js git page and attempted to use this within my javascript. I ran into issues firstly getting the module over HTTP because

<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.X.X/dist/protobuf.js"></script>

uses text/plaintext and fails to return. Adding a type=text/javascript just led to protobuf is not defined.

I then tried to take the project source into my web root, and directly use this:

<script type="text/javascript" src="./js/protobuf-js/src/index.js" ></script>

and:

    import * as protobuf from "./js/protobuf-js/src/index.js";

This worked and the web server returned the file. Now, this is where my understanding reaches it's limits. From what I can tell from the README page on git, it distinctly says

"The library supports CommonJS and AMD loaders and also exports globally as protobuf."

If I look inside index.js I see the following:

var protobuf = module.exports = require("./index-light");

which throws a Module is not defined in ES module scope exception in browser.

Nowhere else online could I find working examples of the protobuf.js being used in commonJS as it states in the git, it all refers to Node.js which I don't want to use as i'm using Java for the webserver side of things.

Am i being really dumb and missing something obvious?

Thanks

CodePudding user response:

There are example in https://github.com/protobufjs/protobuf.js.

a small example:

hello.proto

syntax = "proto3";
message Test{
    string msg=1;
}

test.html

<html lang="en">
<head>
    <script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.11.3/dist/protobuf.js"></script>
</head>
<body>
  <script>
    function test(){
        protobuf.load("hello.proto", function(err, root) {
            var TestMsg = root.lookup('Test');

            var payload = {msg:'hello'};
            var result = TestMsg.verify(payload);

            if(result) throw Error(result);

            var msg = TestMsg.create(payload);
            var binMsg = TestMsg.encode(msg).finish();  // this is the binary protobuf message


            // to handle blob data from server via websocket, you need handle like below
            // event.data.arrayBuffer().then(buf =>{
            //   var msg = TestMsg.decode(new Uint8Array(buf));
            // }

            // deserialize
            var msg2 = TestMsg.decode((binMsg));
            console.log(msg2.toJSON());
            alert(msg2.msg);
        });
    }
  </script>
  <input type="button" value="test" onclick="test()">
</body>
</html>
  • Related