Menu
Open source

Stream.on()

Caution

Starting on k6 v0.49, the experimental module k6/experimental/grpc has been graduated, and its functionality is now available in the k6/net/grpc module. The k6/experimental/grpc is deprecated and will be removed in v0.51.0.

To migrate your scripts, replace all k6/experimental/grpc imports with k6/net/grpc.

Set up handler functions for various events on the GRPC stream.

ParameterTypeDescription
eventstringThe event name to define a handler for.
handlerfunctionThe function to call when the event happens.

Possible events:

Event nameDescription
dataEmitted when the server sends data.
errorEmitted when an error occurs. In case of the error, an Error object sends to the handler function.
endEmitted when the server closes the incoming stream.

Example

JavaScript
import { Client, Stream } from 'k6/experimental/grpc';
import { sleep } from 'k6';

const COORD_FACTOR = 1e7;

const client = new Client();
client.load([], '../../grpc_server/route_guide.proto');

export default () => {
  if (__ITER == 0) {
    client.connect('127.0.0.1:10000', { plaintext: true });
  }

  const stream = new Stream(client, 'main.RouteGuide/RecordRoute');

  // sets up a handler for the data (server sends data) event
  stream.on('data', (stats) => {
    console.log('Finished trip with', stats.pointCount, 'points');
    console.log('Passed', stats.featureCount, 'features');
    console.log('Traveled', stats.distance, 'meters');
    console.log('It took', stats.elapsedTime, 'seconds');
  });

  // sets up a handler for the end event (stream closes)
  stream.on('end', function () {
    // The server has finished sending
    client.close();
    console.log('All done');
  });

  // sets up a handler for the error event (an error occurs)
  stream.on('error', function (e) {
    // An error has occurred and the stream has been closed.
    console.log('Error: ' + JSON.stringify(e));
  });

  sleep(1);
};