Grpc Nodejs server

syntax = "proto3";

package App;

message Empty {};

message Response {
  int32 code = 1;
  string message = 2;
}

service EchoService {
    rpc Greet(Empty) returns (Response);
}

Node server :

const PROTO_PATH = __dirname + '/proto/echo.proto';

const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync(
    PROTO_PATH,
    {
        keepCase: true,
        longs: String,
        enums: String,
        defaults: true,
        oneofs: true
    });
const echo_proto = grpc.loadPackageDefinition(packageDefinition);

/**
 * @param call  proto 定义的函数参数
 * @param callback 第二个为 proto 定义的函数返回的参数
 * @constructor
 */
function Greet(call, callback) {
    callback(null, {code: 0, message: "Hello node gRPC."});
}

function main() {
    const server = new grpc.Server();
    console.log(echo_proto);
    server.addService(echo_proto.App.EchoService.service, {Greet});
    server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
    server.start();
}

main();

Node 端代码会自动编译 protobuf 文件,所以不需要手动生成。

依赖:

    "@grpc/proto-loader": "^0.1.0",
    "async": "^1.5.2",
    "google-protobuf": "^3.0.0",
    "grpc": "^1.11.0",
    "lodash": "^4.6.1",
    "minimist": "^1.2.0"