Eventsedit

The client is an event emitter, this means that you can listen for its event and add additional logic to your code, without need to change the client internals or your normal usage.
You can find the events names by access the events key of the client.

const { events } = require('@elastic/elasticsearch')
console.log(events)

The event emitter functionality can be useful if you want to log every request, response and error that is happening during the use of the client.

const logger = require('my-logger')()
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })

client.on('response', (err, result) => {
  if (err) {
    logger.error(err)
  } else {
    logger.info(result)
  }
})

The client emits the following events:

request

Emitted before sending the actual request to Elasticsearch (emitted multiple times in case of retries).

client.on('request', (err, result) => {
  console.log(err, result)
})

response

Emitted once Elasticsearch response has been received and parsed.

client.on('response', (err, result) => {
  console.log(err, result)
})

sniff

Emitted when the client ends a sniffing request.

client.on('sniff', (err, result) => {
  console.log(err, result)
})

resurrect

Emitted if the client is able to resurrect a dead node.

client.on('resurrect', (err, result) => {
  console.log(err, result)
})

The values of result in request, response and sniff will be:

body: any;
statusCode: number | null;
headers: anyObject | null;
warnings: string[] | null;
meta: {
  context: any;
  name: string;
  request: {
    params: TransportRequestParams;
    options: TransportRequestOptions;
    id: any;
  };
  connection: Connection;
  attempts: number;
  aborted: boolean;
  sniff?: {
    hosts: any[];
    reason: string;
  };
};

While the result value in resurrect will be:

strategy: string;
isAlive: boolean;
connection: Connection;
name: string;
request: {
  id: any;
};