### Start the Server Source: https://github.com/grpc/grpc-node/blob/master/examples/cancellation/README.md Run the server script to start the gRPC server. ```bash node server.js ``` -------------------------------- ### Install @grpc/proto-loader Source: https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md Install the package using npm. ```sh npm install @grpc/proto-loader ``` -------------------------------- ### Install gRPC Node.js Dependencies Source: https://github.com/grpc/grpc-node/blob/master/examples/README.md Clone the gRPC repository and install necessary npm packages for the examples. Ensure Node.js version 8.13.0 or greater is installed. ```sh $ # Get the gRPC repository $ export REPO_ROOT=grpc-node # REPO root can be any directory of your choice $ git clone -b RELEASE_TAG_HERE https://github.com/grpc/grpc-node $REPO_ROOT $ cd $REPO_ROOT $ cd examples $ npm install ``` -------------------------------- ### Install grpc-health-check Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-health-check/README.md Install the package using npm. ```bash npm install grpc-health-check ``` -------------------------------- ### Install @grpc/reflection Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-reflection/README.md Install the gRPC reflection package using npm. ```bash npm install @grpc/reflection ``` -------------------------------- ### Pick First Load Balancing Example Output Source: https://github.com/grpc/grpc-node/blob/master/examples/load_balancing/README.md Output demonstrating the `pick_first` load balancing policy, where all RPCs are directed to a single backend server. ```text this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) ``` -------------------------------- ### Install @grpc/grpc-js Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-js/README.md Install the @grpc/grpc-js package using npm. Node 12 or higher is recommended. ```sh npm install @grpc/grpc-js ``` -------------------------------- ### Configure Protobuf Loading Options Source: https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md Example of an options object to customize protobuf loading behavior, closely approximating the behavior of `grpc.load`. ```js const options = { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true } ``` -------------------------------- ### Generate Route Guide gRPC Code Source: https://github.com/grpc/grpc-node/blob/master/examples/routeguide/static_codegen/README.md Use this command to generate the static gRPC code for the Route Guide service. Ensure you are in the correct directory and have the necessary tools installed. ```sh cd ../protos npm install -g grpc-tools grpc_tools_node_protoc --js_out=import_style=commonjs,binary:../routeguide/static_codegen/ --grpc_out=grpc_js:../routeguide/static_codegen/ route_guide.proto ``` -------------------------------- ### Round Robin Load Balancing Example Output Source: https://github.com/grpc/grpc-node/blob/master/examples/load_balancing/README.md Output demonstrating the `round_robin` load balancing policy, where RPCs are distributed sequentially across available backend servers. ```text this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50052) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50052) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50052) this is examples/load_balancing (from 0.0.0.0:50051) this is examples/load_balancing (from 0.0.0.0:50052) this is examples/load_balancing (from 0.0.0.0:50051) ``` -------------------------------- ### Run gRPC Node.js Server Examples Source: https://github.com/grpc/grpc-node/blob/master/examples/README.md Execute the gRPC server using either dynamic or static code generation. The server will run in the background. ```sh $ # from this directory $ node ./helloworld/dynamic_codegen/greeter_server.js & ``` ```sh $ # OR $ node ./helloworld/static_codegen/greeter_server.js & ``` -------------------------------- ### Install @grpc/grpc-js-xds Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-js-xds/README.md Install the package using npm. Ensure you are using @grpc/grpc-js version 1.13.x or later. ```bash npm install @grpc/grpc-js-xds ``` -------------------------------- ### Get health.proto Path Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-health-check/README.md Obtain the absolute path to the health.proto file from the command line. ```bash node -p 'require("grpc-health-check").protoPath' ``` -------------------------------- ### Start the gRPC Client with Keepalive Tracing Source: https://github.com/grpc/grpc-node/blob/master/examples/keepalive/README.md Execute the client script with specific environment variables to enable detailed tracing for transport and keepalive mechanisms. This is useful for debugging keepalive behavior. ```bash GRPC_TRACE=transport,keepalive GRPC_VERBOSITY=DEBUG node client.js ``` -------------------------------- ### Run gRPC Node.js Client Examples Source: https://github.com/grpc/grpc-node/blob/master/examples/README.md Execute the gRPC client to interact with the running server. Use the client corresponding to the server's code generation method (dynamic or static). ```sh $ # from this directory $ node ./helloworld/dynamic_codegen/greeter_client.js ``` ```sh $ # OR $ node ./helloworld/static_codegen/greeter_client.js ``` -------------------------------- ### Generate gRPC Code with grpc_tools_node_protoc Source: https://github.com/grpc/grpc-node/blob/master/examples/helloworld/static_codegen/README.md Use `grpc_tools_node_protoc` to generate JavaScript and gRPC code from a .proto file. Ensure `grpc-tools` is installed globally and navigate to the directory containing the proto files. ```sh cd ../protos npm install -g grpc-tools grpc_tools_node_protoc --js_out=import_style=commonjs,binary:../helloworld/static_codegen/ --grpc_out=grpc_js:../helloworld/static_codegen/ helloworld.proto ``` -------------------------------- ### Generate TypeScript Types Command Source: https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md Example command to generate TypeScript types using specific options for handling longs, enums, defaults, oneofs, and specifying the gRPC library and output directory. ```sh $(npm bin)/proto-loader-gen-types --longs=String --enums=String --defaults --oneofs --grpcLib=@grpc/grpc-js --outDir=proto/ proto/*.proto ``` -------------------------------- ### Consume Generated TypeScript Types Source: https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md Example of how to import and use the generated TypeScript types in a gRPC server implementation. This includes loading the package definition and adding a service to a gRPC server. ```ts import * as grpc from '@grpc/grpc-js'; import * as protoLoader from '@grpc/proto-loader'; import type { ProtoGrpcType } from './proto/example.ts'; import type { ExampleHandlers } from './proto/example_package/Example.ts'; const exampleServer: ExampleHandlers = { // server handlers implementation... }; const packageDefinition = protoLoader.loadSync('./proto/example.proto'); const proto = (grpc.loadPackageDefinition( packageDefinition ) as unknown) as ProtoGrpcType; const server = new grpc.Server(); server.addService(proto.example_package.Example.service, exampleServer); ``` -------------------------------- ### Run the Client Source: https://github.com/grpc/grpc-node/blob/master/examples/cancellation/README.md Execute the client script to initiate an RPC and demonstrate cancellation. ```bash node client.js ``` -------------------------------- ### Run Server and Client Source: https://github.com/grpc/grpc-node/blob/master/examples/load_balancing/README.md Execute the server and client scripts to observe load balancing in action. ```bash node server.js ``` ```bash node client.js ``` -------------------------------- ### Load Protobuf Definition Synchronously Source: https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md Load a .proto file synchronously and then load the package definition into the gRPC library. Use this method when blocking the event loop is acceptable. ```js const packageDefinition = protoLoader.loadSync(protoFileName, options); const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); ``` -------------------------------- ### Configure Client-Side Compression Source: https://github.com/grpc/grpc-node/blob/master/doc/compression.md Instantiate a client with options to set the default compression algorithm and level for sending and receiving messages. ```javascript client = new ExampleClient("example.com", credentials.createInsecure(), {'grpc.default_compression_algorithm': 2, 'grpc.default_compression_level': 2}); ``` -------------------------------- ### Enable Full Debug Logging Source: https://github.com/grpc/grpc-node/blob/master/examples/debugging/README.md To enable full debug logging, run your code with the GRPC_TRACE and GRPC_VERBOSITY environment variables set to 'all' and 'DEBUG' respectively. ```bash GRPC_TRACE=all GRPC_VERBOSITY=DEBUG ``` -------------------------------- ### Load Protobuf Definition Asynchronously Source: https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md Load a .proto file asynchronously and then load the package definition into the gRPC library. This method is suitable for non-blocking operations. ```js const protoLoader = require('@grpc/proto-loader'); const grpcLibrary = require('grpc'); // OR const grpcLibrary = require('@grpc/grpc-js'); protoLoader.load(protoFileName, options).then(packageDefinition => { const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); }); ``` -------------------------------- ### Add Reflection Service to gRPC Server Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-reflection/README.md Load your gRPC package definition and create a ReflectionService instance. Add this instance to your existing gRPC server to enable reflection capabilities. ```typescript import { ReflectionService } from '@grpc/reflection'; const pkg = protoLoader.load(...); // Load your gRPC package definition as normal // Create the reflection implementation based on your gRPC package and add it to your existing server const reflection = new ReflectionService(pkg); reflection.addToServer(server); ``` -------------------------------- ### Enable Channel Connectivity Tracing in grpc-js Source: https://github.com/grpc/grpc-node/blob/master/TROUBLESHOOTING.md Combine GRPC_VERBOSITY=debug with GRPC_TRACE=connectivity_state to print information about channel state changes. This helps diagnose connectivity issues. ```bash # Print information about channel state changes GRPC_VERBOSITY=debug GRPC_TRACE=connectivity_state ./helloworld_application_using_grpc ``` -------------------------------- ### Enable Multiple Tracers and Debug Logs in grpc-js Source: https://github.com/grpc/grpc-node/blob/master/TROUBLESHOOTING.md Enable logs from multiple internal components like channel, subchannel, and call_stream by specifying them in GRPC_TRACE, alongside debug logging via GRPC_VERBOSITY=debug. ```bash # Print info from 3 different tracers, including tracing logs with log level DEBUG GRPC_VERBOSITY=debug GRPC_TRACE=channel,subchannel,call_stream ./helloworld_application_using_grpc ``` -------------------------------- ### Create TLS Client Credentials Source: https://github.com/grpc/grpc-node/blob/master/examples/encryption/README.md Use `grpc.credentials.createSsl` to generate client-side TLS credentials for secure connections. Ensure you have the CA certificate to verify the server. ```javascript const grpc = require('@grpc/grpc-js'); const PROTO_PATH = __dirname + '/../proto/helloworld.proto'; const client = new hello_proto.Greeter(serverAddress, grpc.credentials.createSsl(rootCert)); ``` -------------------------------- ### Create TLS Server Credentials Source: https://github.com/grpc/grpc-node/blob/master/examples/encryption/README.md Use `grpc.ServerCredentials.createSsl` to generate server-side TLS credentials. This requires the server's certificate and private key. ```javascript const serverCredentials = grpc.ServerCredentials.createSsl(rootCert, { cert_chain: serverCert, key: serverKey, }); ``` -------------------------------- ### Register xDS Support in @grpc/grpc-js Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-js-xds/README.md Register the xDS plugin to enable its functionality. Then, instantiate a gRPC client using the 'xds://' URL scheme. ```typescript import * as grpcJsXds from '@grpc/grpc-js-xds'; grpcJsXds.register(); // ...get a @grpc/grpc-js Client class as usual const client = new MyServiceClient('xds:///example.com:123'); ``` -------------------------------- ### Proto Loader Gen Types CLI Usage Source: https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md Command-line interface for generating TypeScript types. Use this to specify options and input proto files. ```bash proto-loader-gen-types.js [options] filenames... Options: --help Show help [boolean] --version Show version number [boolean] --keepCase Preserve the case of field names [boolean] [default: false] --longs The type that should be used to output 64 bit integer values. Can be String, Number [string] [default: "Long"] --enums The type that should be used to output enum fields. Can be String [string] [default: "number"] --bytes The type that should be used to output bytes fields. Can be String, Array [string] [default: "Buffer"] --defaults Output default values for omitted fields [boolean] [default: false] --arrays Output default values for omitted repeated fields even if --defaults is not set [boolean] [default: false] --objects Output default values for omitted message fields even if --defaults is not set [boolean] [default: false] --oneofs Output virtual oneof fields set to the present field's name [boolean] [default: false] --json Represent Infinity and NaN as strings in float fields. Also decode google.protobuf.Any automatically [boolean] [default: false] --includeComments Generate doc comments from comments in the original files [boolean] [default: false] -I, --includeDirs Directories to search for included files [array] -O, --outDir Directory in which to output files [string] [required] --grpcLib The gRPC implementation library that these types will be used with. If not provided, some types will not be generated [string] --inputTemplate Template for mapping input or "permissive" type names [string] [default: "%s"] --outputTemplate Template for mapping output or "restricted" type names [string] [default: "%s__Output"] --inputBranded Output property for branded type for "permissive" types with fullName of the Message as its value [boolean] [default: false] --outputBranded Output property for branded type for "restricted" types with fullName of the Message as its value [boolean] [default: false] --targetFileExtension File extension for generated files. [string] [default: ".ts"] --importFileExtension File extension for import specifiers in generated code. [string] [default: ""] ``` -------------------------------- ### Provide Retry Policy as Channel Option Source: https://github.com/grpc/grpc-node/blob/master/examples/retry/README.md Instantiate a gRPC client with a retry policy by passing the service configuration as a channel option. This ensures that the client uses the defined retry strategy for its calls. ```javascript const client = new Echo('localhost:50052', grpc.credentials.createInsecure(), { 'grpc.service_config': JSON.stringify(serviceConfig) }); ``` -------------------------------- ### Create mTLS Client Credentials Source: https://github.com/grpc/grpc-node/blob/master/examples/encryption/README.md Generate client credentials for mutual TLS by providing the client's certificate and private key. This allows the client to authenticate itself to the server. ```javascript const clientCredentials = grpc.credentials.createSsl(rootCert, serverCert, serverKey); const client = new hello_proto.Greeter(serverAddress, clientCredentials); ``` -------------------------------- ### Create mTLS Server Credentials Source: https://github.com/grpc/grpc-node/blob/master/examples/encryption/README.md Configure server credentials for mutual TLS by providing CA certificates for client verification and setting `checkClientCertificate` to true. This ensures both server and client authenticate each other. ```javascript const serverCredentials = grpc.ServerCredentials.createSsl(clientCaCert, { cert_chain: serverCert, key: serverKey, }, true); server.bindAsync(serverAddress, serverCredentials, (err, port) => { // ... }); ``` -------------------------------- ### Enable Debug Logs for grpc-js Application Source: https://github.com/grpc/grpc-node/blob/master/TROUBLESHOOTING.md Use GRPC_VERBOSITY=debug to enable debug logs for your application. This setting increases the amount of information printed to stderr. ```bash # Enable debug logs for an application GRPC_VERBOSITY=debug ./helloworld_application_using_grpc ``` -------------------------------- ### Trivial Node gRPC Server Interceptor Source: https://github.com/grpc/grpc-node/blob/master/examples/interceptors/README.md A basic server interceptor demonstrating how to wrap a call object with a ServerInterceptingCall. Use this to intercept incoming operations. ```javascript const interceptor = function(methodDescriptor, call) { const responder = { start: function(next) { const listener = { onReceiveMetadata: function(metadata, next) { next(metadata); }, onReceiveMessage: function(message, next) { next(message); }, onReceiveHalfClose: function(next) { next(); }, onCancel: function() { } }; next(listener); }, sendMetadata: function(metadata, next) { next(metadata); }, sendMessage: function(message, next) { next(message); }, sendStatus: function(status, next) { next(status); } }; return new ServerInterceptingCall(call, responder); } ``` -------------------------------- ### Add Health Check Service to gRPC Server Source: https://github.com/grpc/grpc-node/blob/master/packages/grpc-health-check/README.md Integrate the HealthImplementation into an existing gRPC-node server to enable health checks. Define a status map for services, including the overall server status represented by an empty string key. ```typescript // Import package import { HealthImplementation, ServingStatusMap } from 'grpc-health-check'; // Define service status map. Key is the service name, value is the corresponding status. // By convention, the empty string '' key represents that status of the entire server. const statusMap = { 'ServiceFoo': 'SERVING', 'ServiceBar': 'NOT_SERVING', '': 'NOT_SERVING', }; // Construct the service implementation const healthImpl = new HealthImplementation(statusMap); healthImpl.addToServer(server); // When ServiceBar comes up healthImpl.setStatus('serviceBar', 'SERVING'); ``` -------------------------------- ### Trivial Node gRPC Client Interceptor Source: https://github.com/grpc/grpc-node/blob/master/examples/interceptors/README.md A basic client interceptor demonstrating how to wrap a call object with an InterceptingCall. Use this to intercept outgoing operations. ```javascript const interceptor = function(options, nextCall) { const requester = { start: function(metadata, listener, next) { const listener = { onReceiveMetadata: function(metadata, next) { next(metadata); }, onReceiveMessage: function(message, next) { next(message); }, onReceiveStatus: function(status, next) { next(status); } }; next(metadata, listener); }, sendMessage: function(message, next) { next(messasge); }, halfClose: function(next) { next(); }, cancel: function(message, next) { next(); } }; return new InterceptingCall(nextCall(options), requester); }; ``` -------------------------------- ### Define Retry Policy for gRPC Method Source: https://github.com/grpc/grpc-node/blob/master/examples/retry/README.md Configure a retry policy within the service config for a specific gRPC method. This policy dictates how the client should handle retries, including the number of attempts and backoff strategy. ```javascript const serviceConfig = { loadBalancingConfig: [], methodConfig: [ { name: [ { service: 'grpc.examples.echo.Echo', }, ], retryPolicy: { maxAttempts: 4, initialBackoff: '0.01s', maxBackoff: '0.01s', backoffMultiplier: 1.0, retryableStatusCodes: ['UNAVAILABLE'], }, }, ], }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.