gRPC Basics - Node.js

This tutorial provides a basic Node.js programmer’s introductionto working with gRPC.

By walking through this example you’ll learn how to:

  • Define a service in a .proto file.
  • Use the Node.js gRPC API to write a simple client and server for your service.

It assumes that you have read theOverview and are familiarwithprotocolbuffers. Notethat the example in this tutorial uses theproto3 version of the protocolbuffers language. You can find out more in theproto3 language guide.

Why use gRPC?

Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.

With gRPC we can define our service once in a .proto file and implement clientsand servers in any of gRPC’s supported languages, which in turn can be run inenvironments ranging from servers inside Google to your own tablet - all thecomplexity of communication between different languages and environments ishandled for you by gRPC. We also get all the advantages of working with protocolbuffers, including efficient serialization, a simple IDL, and easy interfaceupdating.

Example code and setup

The example code for our tutorial is ingrpc/grpc/examples/node/dynamic_codegen/route_guide.As you’ll see if you look at the repository, there’s also a very similar-lookingexample ingrpc/grpc/examples/node/static_codegen/route_guide.We have two versions of our route guide example because there are two ways togenerate the code needed to work with protocol buffers in Node.js - one approachuses Protobuf.js to dynamically generate the code at runtime, the other usescode statically generated using the protocol buffer compiler protoc. Theexamples behave identically, and either server can be used with either client.As suggested by the directory name, we’ll be using the version with dynamicallygenerated code in this document, but feel free to look at the static codeexample too.

To download the example, clone the grpc repository by running the followingcommand:

  1. $ git clone -b v1.28.1 https://github.com/grpc/grpc
  2. $ cd grpc

Then change your current directory to examples/node:

  1. $ cd examples/node

You also should have the relevant tools installed to generate the server andclient interface code - if you don’t already, follow the setup instructions inthe Node.js quick start guide.

Defining the service

Our first step (as you’ll know from theOverview) is todefine the gRPC service and the method request and response types usingprotocolbuffers. You cansee the complete .proto file inexamples/protos/route_guide.proto.

To define a service, you specify a named service in your .proto file:

  1. service RouteGuide {
  2. ...
  3. }

Then you define rpc methods inside your service definition, specifying theirrequest and response types. gRPC lets you define four kinds of service method,all of which are used in the RouteGuide service:

  • A simple RPC where the client sends a request to the server using the stuband waits for a response to come back, just like a normal function call.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A server-side streaming RPC where the client sends a request to the serverand gets a stream to read a sequence of messages back. The client reads fromthe returned stream until there are no more messages. As you can see in ourexample, you specify a server-side streaming method by placing the streamkeyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A client-side streaming RPC where the client writes a sequence of messagesand sends them to the server, again using a provided stream. Once the clienthas finished writing the messages, it waits for the server to read them alland return its response. You specify a client-side streaming method by placingthe stream keyword before the request type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectional streaming RPC where both sides send a sequence of messagesusing a read-write stream. The two streams operate independently, so clientsand servers can read and write in whatever order they like: for example, theserver could wait to receive all the client messages before writing itsresponses, or it could alternately read a message then write a message, orsome other combination of reads and writes. The order of messages in eachstream is preserved. You specify this type of method by placing the streamkeyword before both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

Our .proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

Loading service descriptors from proto files

The Node.js library dynamically generates service descriptors and client stubdefinitions from .proto files loaded at runtime.

To load a .proto file, simply require the gRPC proto loader library and use itsloadSync() method, then pass the output to the gRPC library’s loadPackageDefinition method:

  1. var PROTO_PATH = __dirname + '/../../../protos/route_guide.proto';
  2. var grpc = require('grpc');
  3. var protoLoader = require('@grpc/proto-loader');
  4. // Suggested options for similarity to existing grpc.load behavior
  5. var packageDefinition = protoLoader.loadSync(
  6. PROTO_PATH,
  7. {keepCase: true,
  8. longs: String,
  9. enums: String,
  10. defaults: true,
  11. oneofs: true
  12. });
  13. var protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
  14. // The protoDescriptor object has the full package hierarchy
  15. var routeguide = protoDescriptor.routeguide;

Once you’ve done this, the stub constructor is in the routeguide namespace(protoDescriptor.routeguide.RouteGuide) and the service descriptor (which isused to create a server) is a property of the stub(protoDescriptor.routeguide.RouteGuide.service);

Creating the server

First let’s look at how we create a RouteGuide server. If you’re onlyinterested in creating gRPC clients, you can skip this section and go straighttoCreating the client (though you might find it interestinganyway!).

There are two parts to making our RouteGuide service do its job:

  • Implementing the service interface generated from our service definition:doing the actual “work” of our service.
  • Running a gRPC server to listen for requests from clients and return theservice responses.

You can find our example RouteGuide server inexamples/node/dynamic_codegen/route_guide/route_guide_server.js.Let’s take a closer look at how it works.

Implementing RouteGuide

As you can see, our server has a Server constructor generated from theRouteGuide.service descriptor object

  1. var Server = new grpc.Server();

In this case we’re implementing the asynchronous version of RouteGuide,which provides our default gRPC server behaviour.

The functions in route_guide_server.js implement all our service methods.Let’s look at the simplest type first, getFeature, which just gets a Pointfrom the client and returns the corresponding feature information from itsdatabase in a Feature.

  1. function checkFeature(point) {
  2. var feature;
  3. // Check if there is already a feature object for the given point
  4. for (var i = 0; i < feature_list.length; i++) {
  5. feature = feature_list[i];
  6. if (feature.location.latitude === point.latitude &&
  7. feature.location.longitude === point.longitude) {
  8. return feature;
  9. }
  10. }
  11. var name = '';
  12. feature = {
  13. name: name,
  14. location: point
  15. };
  16. return feature;
  17. }
  18. function getFeature(call, callback) {
  19. callback(null, checkFeature(call.request));
  20. }

The method is passed a call object for the RPC, which has the Point parameteras a property, and a callback to which we can pass our returned Feature. Inthe method body we populate a Feature corresponding to the given point andpass it to the callback, with a null first parameter to indicate that there isno error.

Now let’s look at something a bit more complicated - a streaming RPC.listFeatures is a server-side streaming RPC, so we need to send back multipleFeatures to our client.

  1. function listFeatures(call) {
  2. var lo = call.request.lo;
  3. var hi = call.request.hi;
  4. var left = _.min([lo.longitude, hi.longitude]);
  5. var right = _.max([lo.longitude, hi.longitude]);
  6. var top = _.max([lo.latitude, hi.latitude]);
  7. var bottom = _.min([lo.latitude, hi.latitude]);
  8. // For each feature, check if it is in the given bounding box
  9. _.each(feature_list, function(feature) {
  10. if (feature.name === '') {
  11. return;
  12. }
  13. if (feature.location.longitude >= left &&
  14. feature.location.longitude <= right &&
  15. feature.location.latitude >= bottom &&
  16. feature.location.latitude <= top) {
  17. call.write(feature);
  18. }
  19. });
  20. call.end();
  21. }

As you can see, instead of getting the call object and callback in our methodparameters, this time we get a call object that implements the Writableinterface. In the method, we create as many Feature objects as we need toreturn, writing them to the call using its write() method. Finally, we callcall.end() to indicate that we have sent all messages.

If you look at the client-side streaming method RecordRoute you’ll see it’squite similar to the unary call, except this time the call parameterimplements the Reader interface. The call's 'data' event fires every timethere is new data, and the 'end' event fires when all data has been read. Likethe unary case, we respond by calling the callback

  1. call.on('data', function(point) {
  2. // Process user data
  3. });
  4. call.on('end', function() {
  5. callback(null, result);
  6. });

Finally, let’s look at our bidirectional streaming RPC RouteChat().

  1. function routeChat(call) {
  2. call.on('data', function(note) {
  3. var key = pointKey(note.location);
  4. /* For each note sent, respond with all previous notes that correspond to
  5. * the same point */
  6. if (route_notes.hasOwnProperty(key)) {
  7. _.each(route_notes[key], function(note) {
  8. call.write(note);
  9. });
  10. } else {
  11. route_notes[key] = [];
  12. }
  13. // Then add the new note to the list
  14. route_notes[key].push(JSON.parse(JSON.stringify(note)));
  15. });
  16. call.on('end', function() {
  17. call.end();
  18. });
  19. }

This time we get a call implementing Duplex that can be used to read _and_write messages. The syntax for reading and writing here is exactly the same asfor our client-streaming and server-streaming methods. Although each side willalways get the other’s messages in the order they were written, both the clientand server can read and write in any order — the streams operate completelyindependently.

Starting the server

Once we’ve implemented all our methods, we also need to start up a gRPC serverso that clients can actually use our service. The following snippet shows how wedo this for our RouteGuide service:

  1. function getServer() {
  2. var server = new grpc.Server();
  3. server.addProtoService(routeguide.RouteGuide.service, {
  4. getFeature: getFeature,
  5. listFeatures: listFeatures,
  6. recordRoute: recordRoute,
  7. routeChat: routeChat
  8. });
  9. return server;
  10. }
  11. var routeServer = getServer();
  12. routeServer.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  13. routeServer.start();

As you can see, we build and start our server with the following steps:

  • Create a Server constructor from the RouteGuide service descriptor.
  • Implement the service methods.
  • Create an instance of the server by calling the Server constructor withthe method implementations.
  • Specify the address and port we want to use to listen for client requestsusing the instance’s bind() method.
  • Call start() on the instance to start the RPC server.

Creating the client

In this section, we’ll look at creating a Node.js client for our RouteGuideservice. You can see our complete example client code inexamples/node/dynamic_codegen/route_guide/route_guide_client.js.

Creating a stub

To call service methods, we first need to create a stub. To do this, we justneed to call the RouteGuide stub constructor, specifying the server address andport.

  1. new routeguide.RouteGuide('localhost:50051', grpc.credentials.createInsecure());

Calling service methods

Now let’s look at how we call our service methods. Note that all of thesemethods are asynchronous: they use either events or callbacks to retrieveresults.

Simple RPC

Calling the simple RPC GetFeature is nearly as straightforward as calling alocal asynchronous method.

  1. var point = {latitude: 409146138, longitude: -746188906};
  2. stub.getFeature(point, function(err, feature) {
  3. if (err) {
  4. // process error
  5. } else {
  6. // process feature
  7. }
  8. });

As you can see, we create and populate a request object. Finally, we call themethod on the stub, passing it the request and callback. If there is no error,then we can read the response information from the server from our responseobject.

  1. console.log('Found feature called "' + feature.name + '" at ' +
  2. feature.location.latitude/COORD_FACTOR + ', ' +
  3. feature.location.longitude/COORD_FACTOR);

Streaming RPCs

Now let’s look at our streaming methods. If you’ve already readCreating theserver some of this may look very familiar - streaming RPCs areimplemented in a similar way on both sides. Here’s where we call the server-sidestreaming method ListFeatures, which returns a stream of geographicalFeatures:

  1. var call = client.listFeatures(rectangle);
  2. call.on('data', function(feature) {
  3. console.log('Found feature called "' + feature.name + '" at ' +
  4. feature.location.latitude/COORD_FACTOR + ', ' +
  5. feature.location.longitude/COORD_FACTOR);
  6. });
  7. call.on('end', function() {
  8. // The server has finished sending
  9. });
  10. call.on('error', function(e) {
  11. // An error has occurred and the stream has been closed.
  12. });
  13. call.on('status', function(status) {
  14. // process status
  15. });

Instead of passing the method a request and callback, we pass it a request andget a Readable stream object back. The client can use the Readable's'data' event to read the server’s responses. This event fires with eachFeature message object until there are no more messages. Errors in the 'data'callback will not cause the stream to be closed. The 'error' eventindicates that an error has occurred and the stream has been closed. The'end' event indicates that the server has finished sending and no errorsoccured. Only one of 'error' or 'end' will be emitted. Finally, the'status' event fires when the server sends the status.

The client-side streaming method RecordRoute is similar, except there we passthe method a callback and get back a Writable.

  1. var call = client.recordRoute(function(error, stats) {
  2. if (error) {
  3. callback(error);
  4. }
  5. console.log('Finished trip with', stats.point_count, 'points');
  6. console.log('Passed', stats.feature_count, 'features');
  7. console.log('Travelled', stats.distance, 'meters');
  8. console.log('It took', stats.elapsed_time, 'seconds');
  9. });
  10. function pointSender(lat, lng) {
  11. return function(callback) {
  12. console.log('Visiting point ' + lat/COORD_FACTOR + ', ' +
  13. lng/COORD_FACTOR);
  14. call.write({
  15. latitude: lat,
  16. longitude: lng
  17. });
  18. _.delay(callback, _.random(500, 1500));
  19. };
  20. }
  21. var point_senders = [];
  22. for (var i = 0; i < num_points; i++) {
  23. var rand_point = feature_list[_.random(0, feature_list.length - 1)];
  24. point_senders[i] = pointSender(rand_point.location.latitude,
  25. rand_point.location.longitude);
  26. }
  27. async.series(point_senders, function() {
  28. call.end();
  29. });

Once we’ve finished writing our client’s requests to the stream using write(),we need to call end() on the stream to let gRPC know that we’ve finishedwriting. If the status is OK, the stats object will be populated with theserver’s response.

Finally, let’s look at our bidirectional streaming RPC routeChat(). In thiscase, we just pass a context to the method and get back a Duplex streamobject, which we can use to both write and read messages.

  1. var call = client.routeChat();

The syntax for reading and writing here is exactly the same as for ourclient-streaming and server-streaming methods. Although each side will alwaysget the other’s messages in the order they were written, both the client andserver can read and write in any order — the streams operate completelyindependently.

Try it out!

Build the client and server:

  1. $ npm install

Run the server:

  1. $ node ./dynamic_codegen/route_guide/route_guide_server.js --db_path=./dynamic_codegen/route_guide/route_guide_db.json

From a different terminal, run the client:

  1. $ node ./dynamic_codegen/route_guide/route_guide_client.js --db_path=./dynamic_codegen/route_guide/route_guide_db.json