我对JS比较陌生,但对protobuf非常熟悉。我目前正在设计一个由Java服务器托管的web页面,并希望实现它们之间的protobuf通信。
我的问题在浏览器方面。经过一些研究,我找到了protobuf.js git页面,并试图在我的javascript中使用这个页面。我首先遇到了通过HTTP获取模块的问题,因为
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.X.X/dist/protobuf.js"></script>
使用text/plaintext并无法返回。添加一个type=text/javascript只会导致protobuf is not defined。
然后,我尝试将项目源代码放到我的web根目录中,并直接使用以下内容:
<script type="text/javascript" src="./js/protobuf-js/src/index.js" ></script>以及:
import * as protobuf from "./js/protobuf-js/src/index.js";这起作用了,web服务器返回了文件。现在,这就是我理解的极限。从git的自述页面中我可以清楚地看出
"The library supports CommonJS and AMD loaders and also exports globally as protobuf."
如果我查看index.js内部,我会看到以下内容:
var protobuf = module.exports = require("./index-light");它在浏览器中引发Module is not defined in ES module scope异常。
在网上没有其他地方可以找到protobuf.js在commonJS中使用的工作示例,因为它在git中声明,所有这些都是指commonJS中我不想使用的Node.js,因为我在for服务器端使用Node.js。
我是不是真的傻了,错过了一些明显的东西?
谢谢
发布于 2022-07-30 02:09:15
在https://github.com/protobufjs/protobuf.js中有一些例子。
一个小例子:
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>https://stackoverflow.com/questions/73170288
复制相似问题