使用google.protobuf导入的Proto文件 - 导致NodeJS中出现问题

问题描述 投票:0回答:1

我在原型文件中使用google.profobuf。*导入(由go写的GRPC服务器使用)。当使用相同的proto文件在NodeJS中实现GRPC客户端时 - 我遇到了问题。

细节:

GRPC服务器使用的proto文件(用go编写):

tech.proto

syntax = "proto3";

package api;

import "google/protobuf/duration.proto";
import "google/protobuf/empty.proto";

message Info {
    string desc = 1;
    google.protobuf.Duration ttl = 2;
}

service Tech {
    rpc BasicInfo(google.protobuf.Empty) returns (Info) {}
}

当用NodeJ编写的GRPC客户端使用它时:

getTechInfo.js(前几行)

'use strict';

const PROTO_PATH = __dirname + '/../../api/tech.proto';
const grpc = require('grpc');
const apiProto = grpc.load(PROTO_PATH).api;

我收到以下错误:

/Users/././node_modules/protobufjs/dist/protobuf.js:4720
                            throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
                            ^

Error: failed to import '/Users/././api/google/protobuf/duration.proto' in '/Users/././api/register.proto': file not found
    at Builder.ProtoBuf.Builder.BuilderPrototype.import (/Users/././node_modules/protobufjs/dist/protobuf.js:4720:35)
    at Object.ProtoBuf.loadJson (/Users/././node_modules/protobufjs/dist/protobuf.js:5225:26)
    at Object.ProtoBuf.loadProto (/Users/././node_modules/protobufjs/dist/protobuf.js:5128:25)
    at Object.ProtoBuf.loadProtoFile (/Users/././node_modules/protobufjs/dist/protobuf.js:5174:52)
    at Object.load (/Users/././node_modules/grpc/index.js:135:26)
    at Object.<anonymous> (/Users/././src/api/getTechInfo.js:5:23)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)

问题在于proto文件中的导入:

import "google/protobuf/duration.proto";
import "google/protobuf/empty.proto";

解决这些导入的推荐方法是什么?提前致谢。

使用:

Node v8.9.4
"google-protobuf": "^3.5.0",
"grpc": "^1.10.1",
node.js protocol-buffers grpc
1个回答
0
投票

这是gRPC库的一个已知问题,主要记录在this issue中。 grpc.load API不支持轻松加载google/protobuf/*.proto文件。

最简单的解决方案是使用@grpc/proto-loader库,它在加载proto文件时自动包含google/protobuf/*.proto文件。

另一种解决方案是使用grpc-tools预生成可与google-protobuf库一起使用的文件。

© www.soinside.com 2019 - 2024. All rights reserved.