Home

Setting Up a Simple gRPC Service and Client Using Node.js and JavaScript

37 views

Creating a gRPC service using JavaScript typically involves using Node.js, given its robust ecosystem and support for modern JavaScript features. Here’s how you can set up a simple gRPC server and client in JavaScript.

Prerequisites

  1. Install Node.js: Download and install Node.js from nodejs.org.
  2. Install Protocol Buffers Compiler (protoc): Follow the instructions on the Protocol Buffers GitHub page to download and install the Protocol Buffers compiler.

Step-by-Step Guide

  1. Define Service using Protobuf

    Create a file named example.proto:

    syntax = "proto3";
    
    package example;
    
    service Greeter {
      rpc SayHello (HelloRequest) returns (HelloReply);
    }
    
    message HelloRequest {
      string name = 1;
    }
    
    message HelloReply {
      string message = 1;
    }
    
  2. Generate gRPC Code

    Use the protoc compiler to generate the gRPC service code for Node.js:

    mkdir -p out
    protoc --js_out=import_style=commonjs,binary:out --grpc_out=out --plugin=protoc-gen-grpc=`which grpc_tools_node_protoc_plugin` example.proto
    

    This will generate out/example_pb.js and out/example_grpc_pb.js.

  3. Setup Project

    Create a new Node.js project and install the required dependencies:

    mkdir grpc_example
    cd grpc_example
    npm init -y
    npm install @grpc/grpc-js @grpc/proto-loader
    
  4. Create Server

    Create a file named server.js:

    const grpc = require('@grpc/grpc-js');
    const protoLoader = require('@grpc/proto-loader');
    const packageDefinition = protoLoader.loadSync('example.proto', {
      keepCase: true,
      longs: String,
      enums: String,
      defaults: true,
      oneofs: true,
    });
    const exampleProto = grpc.loadPackageDefinition(packageDefinition).example;
    
    function sayHello(call, callback) {
      callback(null, { message: 'Hello ' + call.request.name });
    }
    
    function main() {
      const server = new grpc.Server();
      server.addService(exampleProto.Greeter.service, { SayHello: sayHello });
      server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
        server.start();
        console.log('Server running at http://127.0.0.1:50051');
      });
    }
    
    main();
    
  5. Create Client

    Create a file named client.js:

    const grpc = require('@grpc/grpc-js');
    const protoLoader = require('@grpc/proto-loader');
    const packageDefinition = protoLoader.loadSync('example.proto', {
      keepCase: true,
      longs: String,
      enums: String,
      defaults: true,
      oneofs: true,
    });
    const exampleProto = grpc.loadPackageDefinition(packageDefinition).example;
    
    function main() {
      const client = new exampleProto.Greeter('localhost:50051', grpc.credentials.createInsecure());
      client.SayHello({ name: 'world' }, (error, response) => {
        if (!error) {
          console.log('Greeting:', response.message);
        } else {
          console.error(error);
        }
      });
    }
    
    main();
    
  6. Run the Server and Client

    First, start the server:

    node server.js
    

    Then, in another terminal, run the client:

    node client.js
    

    The client should output:

    Greeting: Hello world
    

Conclusion

This example demonstrates how to create a simple gRPC service and client using Node.js. By defining your service with Protocol Buffers and generating the necessary code, you can leverage gRPC to build efficient and scalable communication between services in JavaScript. This setup takes advantage of the rich Node.js ecosystem and the performance benefits of using gRPC for inter-service communication.